Tricky GROUP BY SQL带有附加约束

时间:2015-07-20 16:58:20

标签: mysql sql

我有一个像这样的“成员”表:

id   status    user_id   created_at
-----------------------------------
1    active    1         2015-07-01
2    active    2         2015-07-01
3    inactive  1         2015-07-04
4    deleted   2         2015-07-04
5    active    3         2015-07-04
6    active    1         2015-07-08
7    inactive  3         2015-07-08

如何在任何给定日期查询所有用户的最新状态?

对于 2015-07-01 ,输出应为:

id   status    user_id   created_at
-----------------------------------
1    active    1         2015-07-01
2    active    2         2015-07-01

对于 2015-07-05 ,输出应为:

id   status    user_id   created_at
-----------------------------------
3    inactive  1         2015-07-04
4    deleted   2         2015-07-04
5    active    3         2015-07-04

对于 2015-07-10 ,输出应为:

id   status    user_id   created_at
-----------------------------------
3    active    1         2015-07-08
4    deleted   2         2015-07-04
5    inactive  3         2015-07-08

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

使用group bywhere一起获取指定日期之前的最新日期,然后加入:

select m.*
from members m join
     (select user_id, max(created_at) as maxca
      from members
      where created_at <= '2015-07-08'  -- or whatever
      group by user_id
     ) mu
     on m.user_id = mu.user_id and m.created_at = mu.maxca;