dongqu2863 2015-08-19 20:13
浏览 146
已采纳

MySQL - 选择时间范围内的行分组日期和ID

I'm having trouble with a query I need to get some data from my db.

I have a table with the following data:

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

I need to get the total amount of users that "played" on a date range, i.e 2015-08-10 to 2015-08-22, grouped by date and user_id. For example, with this data given the result should be:

total_players    date
1                2015-08-19
3                2015-08-20
2                2015-08-21

I've tried this the following query but it doesn't group correctly:

SELECT date, COUNT(*) AS total_players 
FROM plays 
WHERE date BETWEEN '$start_date' AND '$end_date' 
GROUP BY date, user_id

Can anybody help me with the correct query? Thanks everyone in advance.

  • 写回答

2条回答 默认 最新

  • dtzjvj3915 2015-08-19 20:17
    关注
    SELECT date, COUNT(DISTINCT user_id) 
    FROM plays
    WHERE date BETWEEN '$start_date' AND '$end_date' 
    GROUP BY date
    

    Tested locally on test database with your data

    total_players    date
    1                2015-08-19
    3                2015-08-20
    2                2015-08-21
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题