按日历月汇总日期数据

时间:2018-07-17 19:48:17

标签: sql postgresql

说我有一些与用户注册系统有关的数据,以及当他们禁用帐户时(为简单起见,我只写了年/月):

name  | created   | deactivated
------|-----------|--------------
Dan   | 2018 / 2  | 2018 / 5
Mike  | 2018 / 4  | 2018 / 7 
Dave  | 2018 / 5  | NULL

我将如何编写查询,以根据日历年(可追溯至年初)将数据转换为汇总形式,例如:

month     | created  | deactivated
----------|----------|--------------
2018 / 7  | 0        | 1
2018 / 6  | 0        | 0
2018 / 5  | 1        | 1
2018 / 4  | 1        | 0
2018 / 3  | 0        | 0
2018 / 2  | 1        | 0
2018 / 1  | 0        | 0

我已经能够为单列提出这样的内容:

SELECT
  extract(year from created) || ' / ' || extract(month from created) as month,
  count('month')
FROM accounts
GROUP BY month
ORDER BY month;

但是随后,我陷入了如何根据另一个字段添加另一列的问题(我正在created中使用GROUP BY)。此查询还将省略不包含任何数据的月份,并且在没有数据时也不会返回到2018 / 1

1 个答案:

答案 0 :(得分:0)

让我假设month确实是一个约会。如果是这样,请使用generate_series()生成日期,然后使用left joingroup by进行计算:

select gs.mon, sum(created) as created, sum(deactivated) as deactivated
from generate_series('2018-01-01'::date, '2018-07-01'::date, interval '1 month') gs(mon) left join
     ((select created as dte, 1 as created, 0 as deactivated 
       from accounts
      ) union all
      (select deactivated, 0 as created, 1 as deactivated 
       from accounts
      )
     ) a
     on date_trunc('month', a.dte) = gs.mon
group by gs.mon;