Postgres通过代表查询年度销售报告。按月分组

时间:2017-08-09 11:17:02

标签: sql postgresql

我想按销售代表创建一份年度销售报告表,显示所有十二个月。我拥有的数据或多或少与此示例相似:

id | rep | date      | price
----------------------------
1    1     2017-01-01  20
2    1     2017-01-20  44
3    2     2017-02-18  13
4    2     2017-03-08  12
5    2     2017-04-01  88
6    2     2017-09-05  67
7    3     2017-01-31  10
8    3     2017-06-01  74

我需要的结果是这样的:

Rep Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
----------------------------------------------------
1   64  0   0   0   0   0   0   0   0   0   0   0
2   0   13  12  88  0   0   0   0   67  0   0   0
3   10  0   0   0   0   74  0   0   0   0   0   0

编写此查询的最有效方法是什么?

2 个答案:

答案 0 :(得分:2)

一种方式:

select rep,
sum(case when extract('month' from date) = 1 then price else 0 end ) as Jan,
sum(case when extract('month' from date) = 2 then price else 0 end ) as Feb 
-- another months here
from t
group by rep

答案 1 :(得分:1)

一种方法是使用带FILTER的窗口函数:

SELECT DISTINCT 
  "rep",
  COALESCE(SUM(price) FILTER (WHERE extract('month' from "date") = 1) OVER(PARTITION BY "rep"),0) AS Jan,
  COALESCE(SUM(price) FILTER (WHERE extract('month' from "date") = 2) OVER(PARTITION BY "rep"),0) AS Feb
 --....
FROM ta;

<强> Rextester Demo

警告!

您可能也希望按YEAR进行分区,以避免对JAN 2017JAN 2018进行求和。