mysql选择每组前n行

时间:2013-10-03 20:39:07

标签: mysql sql group-by

我读过这篇文章:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/并搜索其他问题

我的表格类似于:

| table.id    | USER.id
----------------------------------------------
| 1           | 101
| 2           | 101
| 3           | 101
| 4           | 101 
| 5           | 101
| 6           | 101
| 7           | 101 
| 8           | 101
| 9           | 101 
| 10          | 101
| 11          | 102
| 12          | 102 
| 13          | 102
| 14          | 102
| 15          | 103 
| 16          | 103
| 17          | 103
| 18          | 103
| 19          | 103
| 20          | 103
| 21          | 103
| 22          | 103 
| 23          | 103
| 24          | 104
| 25          | 104 
| 26          | 104
| 27          | 104
| 28          | 104
| 29          | 104
| 30          | 105
| 31          | 105
| 32          | 105 
| 33          | 106
| 34          | 106

我正在尝试获取由user.id分组的table.id计数,如果user.id的计数大于7,则仅将结果显示为7(也就是将计数结果限制为7)。

在此示例中,结果应为:

| USER.id         | count of table.ID
----------------------------------------
| 101             | 7
| 102             | 4
| 103             | 7
| 104             | 6
| 105             | 3
| 106             | 2

我试过了:

SELECT USERid, COUNT(table.id)
FROM table
WHERE table.id IN (select top 7 table.id from table)
GROUP BY USERid

SELECT USERid, COUNT(table.id)
FROM table
WHERE (
    SELECT COUNT(table.ID) FROM table as t
    WHERE t.id = t.id AND t.USERid <= table.USERid
    ) <= 7
GROUP BY USERid

3 个答案:

答案 0 :(得分:7)

您可以简化查询,并使用LEAST功能

SELECT USERid, LEAST(7, COUNT(*))
FROM table
GROUP BY USERid

来自评论中的问题

SELECT SUM(countByUser) 
FROM
 (SELECT LEAST(7, COUNT(*)) as countByUser
  FROM table
  GROUP BY USERid) c

SqlFiddle

答案 1 :(得分:1)

SELECT userid,
CASE
  WHEN COUNT(*) > 7 THEN 7
  ELSE COUNT(*)
END AS Qty
FROM tbl
GROUP BY userid

答案 2 :(得分:0)

SELECT USERid, case when COUNT(table.id) > 7 
                    then 7 
                    else COUNT(table.id) 
               end
FROM table
GROUP BY USERid