【问题标题】:SQL Date range by month returns in multiple rowsSQL 日期范围按月返回多行
【发布时间】:2020-10-05 02:27:07
【问题描述】:

我希望按月计算条目数。但是,这将返回总计数。

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

如果我无法在其中获取月份,那很好,但我肯定希望拥有它,以便计数有自己的行。这样的事情是如何实现的?

【问题讨论】:

  • 它返回总数,因为您使用星号通配符和 or 运算符。基本上,你是在告诉它where dateAdded between '2020-01-01 00:00:00' and '2020-02-29 23:59:59');

标签: mysql sql date group-by count


【解决方案1】:
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;

【讨论】:

    【解决方案2】:

    这是一个直接聚合查询,您想计算每个月存在多少条记录。

    你可以这样做:

    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
    

    第一列为您提供数据汇总的月份的第一天 - 这似乎比仅月份名称更相关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-24
      • 2014-08-16
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2013-11-01
      相关资源
      最近更新 更多