小编典典

mysql选择每组的前n行

sql

我已阅读这篇文章: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

阅读 139

收藏
2021-03-23

共1个答案

小编典典

您可以简化查询,并使用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

2021-03-23