簡體   English   中英

SQL查詢多個年份中按月計數

[英]SQL Query for count by month over multiple years

我一直在使用下面的查詢來按月對我進行記錄計數。 在特定年份效果良好。

但是,如果我想比較2018年1月至2019年1月的計數會有些痛苦。尤其是當我要繪制圖形時。

我如何調整此值,這樣我可以給出跨度為1月18日,2月18日..... Jan 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'
Please check below query, is this relevant?

大段引用

選擇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)作為2月,計數(當to_char(t.order_date,'MM')= 3時,則1 END)作為Mar,count(當to_char(t.order_date,'MM')= '04',然后1 END)作為四月,計數(當to_char(t.order_date,'MM')= 5時,然后1 END)作為5月,計數(在to_char(t.order_date,'MM')= “ 06”,然后1 END)作為六月,計數(當to_char(t.order_date,'MM')= 7時,然后1 END)作為7月,count(當to_char(t.order_date,'MM')= '08'然后1 END)作為8月,count(case to_char(t.order_date,'MM')='09'然后1 END)作為Sep,count(case to_char(t.order_date,'MM')= '10'然后1 END)作為十月,count(case to_char(t.order_date,'MM')='11'然后1 END)作為Nov,count(case to_char(t.order_date,'MM')= '12',然后1 END),作為Dec FROM事務中的t,其中('2018','2019')中的to_char(order_date,'YYYY')
按to_char(order_date,'YYYY')分組;

大段引用

您可以通過結合以下方式按時間戳對數據進行“存儲桶”處理:

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

您想要結果在不同的行上嗎?

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM