简体   繁体   English

MySQL查询对按日期范围分组的行进行计数

[英]MySQL query to count rows grouped by date range

all. 所有。 I have a table with a date column that is either null or contains the date of an event. 我有一个表,其中的日期列为null或包含事件的日期。 I am trying to get a count of how many of those dates fall within a given range (eg first of the month to last day of the month) and then group by that range (ie group by month) 我正在尝试计算这些日期中有多少属于给定范围(例如,每月的第一天到该月的最后一天),然后按该范围分组(即按月分组)

If I were to do it for a single month, it would look like this: 如果我要这样做一个月,它将看起来像这样:

SELECT count(*)
FROM my_table
WHERE my_table.event_date > 1530403200 and my_table.event_date < 1530403200
/* 7/1/2018 to 7/31/2018 */

So what I'd really like is a query to give me results grouped by month with the count of those total rows within each month, like: 因此,我真正想要的是一个查询,该查询将按月分组的结果与每个月内这些行的总数进行比较,例如:

:
6/1/2018 - 6/30/2018, 8650
7/1/2018 - 7/31/2018, 9180
:
etc.

Thank you for any advice. 感谢您的任何建议。

You can use something like the following: 您可以使用如下所示的内容:

SELECT
    MONTH(FROM_UNIXTIME(event_date)) AS month,
    MIN(FROM_UNIXTIME(event_date)) AS first_date,
    MAX(FROM_UNIXTIME(event_date)) AS last_date, 
    COUNT(*) AS cnt_dates
FROM my_table
WHERE FROM_UNIXTIME(my_table.event_date) > '2018-08-01' 
    AND FROM_UNIXTIME(my_table.event_date) < '2018-08-15' 
    AND NOT my_table.event_date IS NULL
GROUP BY MONTH(FROM_UNIXTIME(event_date))

demo: https://www.db-fiddle.com/f/nNVBtJgpKkiCcf7B9GPCEN/0 演示: https : //www.db-fiddle.com/f/nNVBtJgpKkiCcf7B9GPCEN/0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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