gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:11:03 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com