我有以下查询来获取每月的用户数量:
SELECT count(user_id) from subs
where (started_at between @start_date and @start_date + interval 1 month
or (expires_at>@start_date + interval 1 month and started_at<@start_date))
如果我们有以下数据库:
用户 ID 开始时间、到期时间
================================
1 2015-01-01 2015-12-31
2 2015-01-01 2015-01-03
3 2015-02-01 2015-02-28
4 2015-03-01 2015-03-31
5 2015-04-01 2015-04-31
6 2015-04-01 2016-04-01
7 2015-05-01 2015-05-09
我需要一个将返回下表的查询:
2015年1月2日
2015-02 - 2(因为其中一条 1 月记录直到 12 月才会过期)
2015年3月2日
2015年4月3日
2015年5月3日
等等
那么在一次查询中获取此结果的有效方法是什么?
最佳答案
你可能想要这样的东西:
SELECT YEAR(started_at) as 'Year',
MONTH(started_at) as 'Month',
COUNT(user_id) as 'Users'
FROM subs
GROUP BY YEAR(started_at),MONTH(started_at);
请注意,如果某个月没有用户,则此查询将不会返回该月的条目。如果您还想包含 0 个用户的月份,则需要更复杂的查询;检查this了解更多信息。
关于mysql - 对多个日期运行复杂的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36368311/