可能重复:
How do I select a fixed number of rows for each group?
例如......如果我有这个表(按颜色排序):
--------------
| 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 |
--------------
答案 0 :(得分: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;