2015-09-12 74 views
0

我有一個表有以下的列:如何在Postgres中爲同一列創建兩列總和?

Type | Date | Amount 

我用SUM函數在「總額」列添加的值(如SUM1)當類型具有如「E」值。 這裏是我的查詢:

select 
    to_char("Date", 'Mon') as mon, 
    extract(year from "Date") as yyyy, 
    sum("Amount") as SUM1 
from "Transactions" 
where "Type" LIKE 'E%' and "Date" between '01/01/2015' and '08/31/2015' 
group by 1,2 
order by yyyy, mon; 

這導致行,如:

mon | yyyy | SUM1 

我想怎麼辦,但是,也顯示另一金額列(SUM2),以顯示總和從「量」,其中「類型」就像是「P」增加值,所以表示像行:

mon | yyyy | SUM1 | SUM2 

回答

1

取決於您的PostgreSQL版本。隨着舊的,你可以做一個條件的總和與CASE

select to_char("Date", 'Mon') as mon, 
extract(year from "Date") as yyyy, 
sum(CASE WHEN "Type" LIKE 'E%' then "Amount" ELSE 0 END) as SUM1, 
sum(CASE WHEN "Type" LIKE 'P%' then "Amount" ELSE 0 END) as SUM2 
from "Transactions" 
where "Date" between '01/01/2015' and '08/31/2015' 
group by 1,2 
order by yyyy, mon; 

或者,如果你正在使用PostgreSQL 9.4或更新版本,你可以使用更好FILTER語法:

select to_char("Date", 'Mon') as mon, 
extract(year from "Date") as yyyy, 
sum("Amount") FILTER (WHERE "Type" LIKE 'E%') as SUM1, 
sum("Amount") FILTER (WHERE "Type" LIKE 'P%') as SUM2 
from "Transactions" 
where "Date" between '01/01/2015' and '08/31/2015' 
group by 1,2 
order by yyyy, mon; 
1

可以使用CASE表達式作爲參數傳遞給求和函數選擇什麼被概括成這樣:

select 
    to_char("Date", 'Mon') as mon, 
    extract(year from "Date") as yyyy, 
    sum(case when "Type" LIKE 'E%' then "Amount" else 0 end) as SUM1, 
    sum(case when "Type" LIKE 'P%' then "Amount" else 0 end) as SUM2 
from "Transactions" 
where "Date" between '01/01/2015' and '08/31/2015' 
    and "Type" like 'E%' or "Type" like 'P%' 
group by 1,2 
order by yyyy, mon; 
相關問題