【问题标题】:How do I convert a monthly report to a quarterly report in PostgreSQL如何在 PostgreSQL 中将月度报告转换为季度报告
【发布时间】:2020-06-15 03:16:15
【问题描述】:

目前在月度报告中。我希望它有 4 个季度 Q1、Q2、Q3、Q4 而不是一月、二月、三月、四月、五月、六月、七月等。

代码如下:

create table sales(year int, month int, qty int);
insert into sales values(2007, 1, 1000);
insert into sales values(2007, 2, 1500);
insert into sales values(2007, 7, 500);
insert into sales values(2007, 11, 1500);
insert into sales values(2007, 12, 2000);
insert into sales values(2008, 1, 1000);

select * from crosstab(
  'select year, month, qty from sales order by 1',
  'select m from generate_series(1,12) m'
) as (
  year int,
  "Jan" int,
  "Feb" int,
  "Mar" int,
  "Apr" int,
  "May" int,
  "Jun" int,
  "Jul" int,
  "Aug" int,
  "Sep" int,
  "Oct" int,
  "Nov" int,
  "Dec" int
);

【问题讨论】:

    标签: sql postgresql pivot


    【解决方案1】:

    我只会使用条件聚合:

    select year,
           sum(qty) filter (where month between 1 and 3) as q1,
           sum(qty) filter (where month between 4 and 6) as q2,
           sum(qty) filter (where month between 7 and 9) as q3,
           sum(qty) filter (where month between 10 and 12) as q4
    from t
    group by year;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-16
      • 2012-04-18
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多