2015-10-18 83 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