2

可能重复:
如何为每个组选择固定数量的行?

例如......如果我有这个表(按颜色排序):

--------------
| id | color |
--------------
| 95 | red   |
| 7  | red   |
| 44 | red   |
| 46 | red   |
| 49 | red   |
| 24 | green |
| 37 | green |
| 91 | green |
| 88 | green |
| 44 | blue  |
| 10 | blue  |
| 11 | blue  |
--------------

有没有办法让我从每种颜色中获取 2 行?例子:

--------------
| id | color |
--------------
| 7  | red   |
| 44 | red   |
| 24 | green |
| 37 | green |
| 10 | blue  |
| 11 | blue  |
--------------
4

1 回答 1

8

你可以有这样的东西,

SELECT id, color
FROM   TableName a
WHERE 
(
   SELECT COUNT(*) 
   FROM   TableName AS f
   WHERE  f.color = a.color AND f.id <= a.id
) <= 2;
于 2013-01-04T01:35:57.950 回答