Postgres列值分配

时间:2015-10-18 14:13:54

标签: postgresql

我为我的团队运行收入查询,但我们会与另一个团队分配收入。但是,当我在Postgress中运行查询时,我不知道如何分配列的值,这样我就不会获得100%的收入,我应该与其他3个团队分开(我应该只占收入的25%)。以下是我的询问:

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");

如您所见,我从“交易”表中获取数据。收入来自3个客户,C021,C031和C041,并加在一起以形成“收入”列。

但是,我只想计算每位客户的25%,以便加在一起的价值仅占每位客户收入的25%。

1 个答案:

答案 0 :(得分: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"