简体   繁体   中英

SQL Server to PostgreSQL Sum Function

I have the following code written for SQL Sever . The objetive of it is to consult any bills with their products, and total amounts per article:

Create procedure sp_cons_fact (@id_fact int) as
Begin
     Select * from v_det_fact_art where id_fact=@id_fact
     Select sum(costo_x_art) as Tot_x_fact
     from v_det_fact_art where id_fact=@id_fact
end

For PostgreSQL,I have divided that code into 2 blocks. The first block:

SELECT * 
    From v_det_fact_art 
    WHERE id_fact=id_factura ;

If I change id_factura to 1, it shows:

首先选择

The second block:

SELECT sum(costo_x_art) as Tot_x_Fact 
    From v_det_fact_art 
    WHERE id_fact = id_factura ;

If I change id_factura to 1, it shows:

第二选择

v_det_fact_art is a view that has:

视图

What I would expect to have is: 最后

As you can see, the column tagged as tot_x_fact is the sum of the content of costo_x_art of each id_fact element (in this case id_fact element 1)

70003.22 + 300 = 70303.22 in both cases

Thanks a lot!

Here is an example -

SELECT * FROM MYT;
 id | val 
----+-----
  1 |  10
  1 |  20
  1 |  30
  2 |  10
  2 |  40
(5 rows)

create function myfunc(x int) returns table (id int, value int, sum_val bigint)
as $$
 WITH TMP AS (
 SELECT sum(val) as Tot_x_Fact 
     From myt 
     WHERE id  = $1
     ) 
     select * from  myt vdfa CROSS JOIN tmp WHERE vdfa.id = $1;
  $$ LANGUAGE SQL;
CREATE FUNCTION
pgp=# SELECT MYFUNC(1);
  myfunc   
-----------
 (1,10,60)
 (1,20,60)
 (1,30,60)
(3 rows)


SELECT MYFUNC(2);
  myfunc   
-----------
 (2,10,50)
 (2,40,50)
(2 rows)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM