[英]SQL Server to PostgreSQL Sum Function
我為SQL Sever編寫了以下代碼。 它的目標是查詢與產品相關的任何賬單,以及每篇文章的總金額:
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
對於PostgreSQL,我已將該代碼分為2個塊。 第一塊:
SELECT *
From v_det_fact_art
WHERE id_fact=id_factura ;
如果將id_factura更改為1,則顯示:
第二塊:
SELECT sum(costo_x_art) as Tot_x_Fact
From v_det_fact_art
WHERE id_fact = id_factura ;
如果將id_factura更改為1,則顯示:
v_det_fact_art是具有以下內容的視圖:
我期望擁有的是:
如您所見,標記為tot_x_fact的列是每個id_fact元素(在本例中為id_fact元素1)的costo_x_art內容的總和
兩種情況下70003.22 + 300 = 70303.22
非常感謝!
這是一個例子-
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.