【问题标题】:Postgres query for annual sales report by rep. grouped by monthPostgres 查询代表的年度销售报告。按月分组
【发布时间】:2017-08-09 11:17:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    一种方式:

    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
    

    【讨论】:

      【解决方案2】:

      一种方法是使用带有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 相加。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-12
        相关资源
        最近更新 更多