[英]Group by month with date time in sql
暈,我想按月(月份開始日期)計算數據和分組,然后顯示日期時間,知道嗎?
表_a
timestamp
2020-11-28 04:00:00
2020-11-28 05:00:00
2020-12-29 01:00:00
2020-12-29 02:00:00
2020-12-29 03:00:00
預期結果:
timestamp count
2020-11-01 00:00:00 2
2020-12-01 00:00:00 3
我的查詢是:
SELECT STR_TO_DATE(DATE_FORMAT(timestamp, '%Y-%m-dd HH'), '%Y-%m-dd HH'), count(*) as count
from table_a
但我的結果是:
timestamp count
2020-11-00 2
2020-12-00 3
您可以使用:
select str_to_date(concat_ws('-', year(timestamp), month(timestamp), 1)) as yyyymm,
count(*)
from table_a
group by yyyymm;
我group by month(timestamp)
解決了這個問題,我忽略了記錄,重要的是按月分組,這是我的完整查詢:
SELECT timestamp, count(*) as count
from table_a
group by month(timestamp)
然后 output 顯示:
timestamp count
2020-11-01 04:00:00 2
2020-12-01 01:00:00 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.