MYSQL选择group by并限制每个组,其中created_at在本周内

时间:2016-10-03 15:25:23

标签: mysql greatest-n-per-group

以下是我的数据库表。

id    user_id    group_id    created_at 
 1    1          1           2016-09-29
 2    1          2           2016-10-02
 3    1          3           2016-10-02
 4    1          4           2016-10-03
 5    1          5           2016-10-03

 6    2          1           2016-01-02
 7    2          2           2016-01-02
 8    2          3           2016-01-03

 9    3          1           2016-09-29
10    3          2           2016-09-30
11    3          3           2016-10-02
12    3          4           2016-10-02
13    3          5           2016-10-03

下面是我的SQL查询。

SELECT myTable.* 
FROM myTable 
INNER JOIN (
    SELECT id 
    FROM myTable 
    GROUP BY id 
) group_max 
ON myTable.id = group_max.id 
WHERE YEARWEEK(myTable.add_time) = YEARWEEK(NOW()) 
ORDER BY myTable.user_id ASC, myTable.add_time ASC

通过上述查询,我​​得到以下结果。

id    user_id    group_id    created_at 
 4    1          4           2016-10-03
 5    1          5           2016-10-03
 2    1          2           2016-10-02
 3    1          3           2016-10-02

 8    2          3           2016-01-03
 6    2          1           2016-01-02
 7    2          2           2016-01-02

13    3          5           2016-10-03
11    3          3           2016-10-02
12    3          4           2016-10-02

如何按user_id选择最近2条最近的记录(本周内),如下所示。

id    user_id    group_id    created_at 
 5    1          5           2016-10-03
 4    1          4           2016-10-03

 8    2          3           2016-01-03
 7    2          2           2016-01-02

13    3          5           2016-10-03
12    3          4           2016-10-02

1 个答案:

答案 0 :(得分:0)

下面是工作的SQL查询。

SELECT a.* 
FROM myTable AS a 
WHERE (
    SELECT COUNT(*) 
    FROM myTable AS b 
    WHERE b.user_id = a.user_id AND b.created_at >= a.created_at
) <= 3 
AND YEARWEEK(a.created_at) = YEARWEEK(NOW()) 
ORDER BY a.user_id ASC, a.created_at ASC