mysql - 对多个日期运行复杂的查询

标签 mysql

我有以下查询来获取每月的用户数量:

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/

相关文章:

mysql - 如何在 INNER JOIN 语句中使用括号

java - 如何与3张 table 进行通信

php - 如何将两个 UPDATE 查询合并为一个不同的 WHERE 和 SET?

MySQL选择所有最后添加的查询

php - 如何用php重复进行select查询?

MySQL集群错误: Lock wait timeout exceeded

mysql - 使用 Min(ID) 删除同义词对

php - 如何计算 my_sql

Mysql子查询返回不正确的结果

Python&Peewee - 动态 where 子句