SQL查询多个年份中按月计数

时间:2019-03-07 23:57:20

标签: sql postgresql

我一直在使用下面的查询来按月对我进行记录计数。在特定年份效果良好。

但是,如果要比较从2018年1月到2019年1月的计数,会有些痛苦。特别是如果要绘制图形。

我应该如何调整这一点,以便可以通过给出跨度的年数来获得1月18日,2月18日,... 1月19日的结果。

这是Postgres 9.6

谢谢!

SELECT
  count(case when to_char(t.order_date, 'MM') = '01' then 1 END) as Jan,
  count(case when to_char(t.order_date, 'MM') = '02' then 1 END) as Feb,
  count(case when to_char(t.order_date, 'MM') = '03' then 1 END) as Mar,
  count(case when to_char(t.order_date, 'MM') = '04' then 1 END) as Apr,
  count(case when to_char(t.order_date, 'MM') = '05' then 1 END) as May,
  count(case when to_char(t.order_date, 'MM') = '06' then 1 END) as June,
  count(case when to_char(t.order_date, 'MM') = '07' then 1 END) as Jul,
  count(case when to_char(t.order_date, 'MM') = '08' then 1 END) as Aug,
  count(case when to_char(t.order_date, 'MM') = '09' then 1 END) as Sep,
  count(case when to_char(t.order_date, 'MM') = '10' then 1 END) as Oct,
  count(case when to_char(t.order_date, 'MM') = '11' then 1 END) as Nov,
  count(case when to_char(t.order_date, 'MM') = '12' then 1 END) as Dec
FROM transactions as t
WHERE to_char(t.order_date, 'YYYY') = '2019'

3 个答案:

答案 0 :(得分:1)

Please check below query, is this relevant?
  

Blockquote

选择       to_char(order_date,'YYYY'),       count(to_char(t.order_date,'MM')='01'然后1 END的情况)为Jan,       count(to_char(t.order_date,'MM')='02'然后1 END的情况)为Feb,       count(to_char(t.order_date,'MM')='03'然后1 END的情况)为Mar,       count(to_char(t.order_date,'MM')='04'然后1 END的情况)为Apr,       计数(当to_char(t.order_date,'MM')='05'然后1 END的情况)为May,       计数(当to_char(t.order_date,'MM')='06'然后1 END的情况)为六月,       count(to_char(t.order_date,'MM')='07'然后1 END的情况)为Jul,       count(to_char(t.order_date,'MM')='08'然后1 END的情况)为Aug,       计数(当to_char(t.order_date,'MM')='09'然后1 END的情况)为Sep,       count(to_char(t.order_date,'MM')='10'然后1 END的情况)为十月,       count(to_char(t.order_date,'MM')='11'然后1 END的情况)为Nov,       计数(当to_char(t.order_date,'MM')='12'然后1 END的情况)为Dec       FROM事务作为t(在('2018','2019')中to_char(order_date,'YYYY')的地方
      按to_char(order_date,'YYYY')分组;

  

Blockquote

答案 1 :(得分:0)

您可以通过结合以下方式按时间戳对数据进行“存储桶”操作:

SELECT
    date_trunc('month', t.order_date) AS order_month,
    count(t.order_id) AS count
FROM transaction AS t
GROUP BY order_month
ORDER BY order_month

然后由您决定将结果限制在什么年:

SELECT
    date_trunc('month', t.order_date) AS order_month,
    count(t.order_id) AS count
FROM transaction AS t
WHERE
    date_part('year', t.order_date) = 2019
GROUP BY order_month
ORDER BY order_month

答案 2 :(得分:0)

您想要结果在不同的行吗?

SELECT to_char(t.order_date, 'YYYY') = '2019',
       count(*) filter (to_char(t.order_date, 'MM') = '01') as Jan,
       count(*) filter (to_char(t.order_date, 'MM') = '02') as Feb,
       . . .
       count(*) filter (to_char(t.order_date, 'MM') = '12') as Dec
FROM transactions as t
GROUP BY to_char(t.order_date, 'YYYY') = '2019'