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条)

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法