sql date range by month返回多行

vi4fp9gy  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(280)

我想知道每个月的参赛人数。但是,这将返回总计数。

select count(*) from TBL_NAME 
  where (dateAdded between '2020-01-01 00:00:00' and '2020-01-31 23:59:59') or
  (dateAdded between '2020-02-01 00:00:00' and '2020-02-29 23:59:59');

我希望是这样的。
月-----计数
一月——500
二月——600
如果我不能把这个月放进去,那很好,但我绝对希望有它,这样伯爵就有自己的一行了。这样的事情是如何实现的?

vdgimpew

vdgimpew1#

这是一个直接的聚合查询,您需要计算每个月存在多少条记录。
你可以做:

select
    date_format(dateAdded, '%Y-%m-01') start_of_month,
    count(*) cnt
from tbl_name
where dateAdded >= '2020-01-01' and dateAdded < '2020-03-01'
group by start_of_month

第一列给出了一个月的第一天,这个月的第一天数据被聚合了,这似乎比只有月份名更为相关。

iszxjhcz

iszxjhcz2#

SELECT SUM(dateAdded between '2020-01-01 00:00:00' and '2020-01-31 23:59:59'),
       SUM(dateAdded between '2020-02-01 00:00:00' and '2020-02-29 23:59:59') 
FROM tbl_name 
WHERE (dateAdded between '2020-01-01 00:00:00' and '2020-02-29 23:59:59');

或者

SELECT MONTHNAME(dateAdded), COUNT(*) 
FROM tbl_name 
WHERE (dateAdded between '2020-01-01 00:00:00' and '2020-02-29 23:59:59')
GROUP BY 1;

相关问题