我的示例表:
+----------+---------------------+
| username | time |
+----------+---------------------+
| john | 2013-02-04 17:39:43 |
| john | 2013-02-03 00:21:31 |
| peter | 2013-02-02 15:04:53 |
| grace | 2013-02-02 03:57:43 |
| peter | 2013-02-03 15:36:15 |
+----------+---------------------+
此表记录用户的活动。我需要计算上次活动日期超过30天的用户数量。
我开发了这个查询:
SELECT
username,
MAX(time),
DATEDIFF(NOW(), MAX(time)) as diff
FROM tracking
GROUP BY username
HAVING diff > 30
有效地返回活动超过30天的用户列表,以及最后一次活动的日期。
但我需要此列表的 count ,而不是列表本身。我有什么方法可以统计这份清单吗?
备注:
答案 0 :(得分:2)
就像那样?
Select count(*) as Num FROM
(
SELECT
username,
MAX(time),
DATEDIFF(NOW(), MAX(time)) as diff
FROM tracking
GROUP BY username
HAVING diff > 30
)
答案 1 :(得分:2)
这是一种相对简单的方法:
SELECT count(distinct username) -
count(distinct case when DATEDIFF(NOW(), time) <= 30 then username end) as numusers
FROM tracking
这会占用用户总数,并减去过去30天内有活动的人数。