我遇到了一个查询问题,我需要从我的数据库中获取一些数据。
我有一张包含以下数据的表格:
id user_id game_id date
1 1 1 2015-08-19
2 1 2 2015-08-19
3 1 3 2015-08-19
4 2 1 2015-08-20
5 2 2 2015-08-20
6 1 1 2015-08-20
7 1 1 2015-08-20
8 3 1 2015-08-20
9 2 1 2015-08-21
10 1 1 2015-08-21
11 1 2 2015-08-21
12 2 1 2015-08-21
我需要获得在日期范围内“播放”的用户总数,即2015-08-10到2015-08-22,按日期和user_id分组。 例如,根据给定的数据,结果应为:
total_players date
1 2015-08-19
3 2015-08-20
2 2015-08-21
我已尝试过以下查询,但未正确分组:
SELECT date, COUNT(*) AS total_players
FROM plays
WHERE date BETWEEN '$start_date' AND '$end_date'
GROUP BY date, user_id
有人可以帮我正确查询吗? 提前谢谢大家。
答案 0 :(得分:2)
SELECT date, COUNT(DISTINCT user_id)
FROM plays
WHERE date BETWEEN '$start_date' AND '$end_date'
GROUP BY date
使用您的数据在测试数据库上进行本地测试
total_players date
1 2015-08-19
3 2015-08-20
2 2015-08-21
答案 1 :(得分:0)
http://sqlfiddle.com/#!9/08957/3
SELECT `date`, COUNT(DISTINCT user_id) AS total_players
FROM plays
GROUP BY `date`
或
SELECT `date`, COUNT(DISTINCT user_id) AS total_players
FROM plays
WHERE date BETWEEN '$start_date' AND '$end_date'
GROUP BY `date`