2015-10-18 67 views
0

我爲我的團隊運行收入查詢,但我們與另一個團隊分攤收入。但是,當我在Postgress中運行查詢時,我不知道如何分配列的價值,以致於我不能獲得我應該與另外3個其他團隊分攤的收入的100% (我應該只計算收入的25%)。以下是我的查詢:Postgres列值分配

select to_char("Date", 'Mon/YYYY') as "Date", 
sum("Amount") FILTER (WHERE 
("Type" = 'C021') or --Shared with 3 other teams, only count 25% 
("Type" = 'C031') or --Shared with 3 other teams, only count 25% 
("Type" = 'C041') or --Shared with 3 other teams, only count 25% 
) 
as "Revenue", 
from "Transactions" 
where "Date" between '01/01/2015' and '12/31/2015' 
group by 1 
order by min("Date"); 

正如您所看到的,我從「Transactions」表中獲取數據。收入來自3個客戶,C021,C031和C041,並加在一起構成「收入」列。

但是,我想只計算每個客戶的25%,這樣一起添加的值僅佔每個客戶收入的25%。

回答

1

假設還有其他類型的代碼需要100%的收入,您需要聯合而不是過濾器。

select to_char("Date", 'Mon/YYYY') as "Date", .25 * sum("Amount") as sub_total 
from "Transactions" 
where "Type" in ('C021', 'C031', 'C041') 
group by "Date" 
union 
-- 100% of revenue for all other type codes. Adjust for your 
-- actual situation. 
select to_char("Date", 'Mon/YYYY') as "Date", sum("Amount") 
from "Transactions" 
where "Type" not in ('C021', 'C031', 'C041') 
group by "Date" 

您可能需要調整第二個WHERE子句。

如果你只想要總數,這將每月返回一行。表達式to_char("Date", 'YYYY-mm')比較常見;它作爲一個字符串正確排序。

select "Date", sum(sub_total) as total 
from (select to_char("Date", 'YYYY-mm') as "Date", .25 * sum("Amount") as sub_total 
     from "Transactions" 
     where "Type" in ('C021', 'C031', 'C041') 
     group by "Date" 
     union 
     select to_char("Date", 'YYYY-mm') as "Date", sum("Amount") 
     from "Transactions" 
     where "Type" not in ('C021', 'C031', 'C041') 
     group by "Date") as subtotals 
group by "Date" 
order by "Date" 
+0

這工作,謝謝。並感謝關於日期的提示。 – Piechartking