简体   繁体   English

按月分组,日期时间为 sql

[英]Group by month with date time in sql

halo i want to count the data and group by month (month start date) then show in date time, any idea?晕,我想按月(月份开始日期)计算数据和分组,然后显示日期时间,知道吗?

table_a表_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

expected result:预期结果:

timestamp             count
2020-11-01 00:00:00     2
2020-12-01 00:00:00     3

my query is:我的查询是:

SELECT STR_TO_DATE(DATE_FORMAT(timestamp, '%Y-%m-dd HH'), '%Y-%m-dd HH'), count(*) as count
from table_a

but my results was:但我的结果是:

timestamp    count
2020-11-00     2
2020-12-00     3

You can use:您可以使用:

select str_to_date(concat_ws('-', year(timestamp), month(timestamp), 1)) as yyyymm,
       count(*)
from table_a
group by yyyymm;

i fixed the question with add group by month(timestamp) , im ignored the minuted, the important things is group by month, here are my full query:group by month(timestamp)解决了这个问题,我忽略了记录,重要的是按月分组,这是我的完整查询:

SELECT timestamp, count(*) as count
from table_a 
group by month(timestamp)

then the output show:然后 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM