這有點難度,因爲MySQL沒有Row_Number(),所以你需要模擬它。一種方法是使用自連接和計數。你也可以使用@rownumber
technique described here
在我的例子我用animal_id找到最近的,但你可能要聯接條件更改爲AND t1.born_on < t2.born_on
SELECT farmer_id
FROM
(
SELECT t1.farmer_id,
t1.animal_id,
Count(t2.animal_id) rn,
t1.type
FROM table1 t1
LEFT JOIN table1 t2
ON t1.farmer_id = t2.farmer_id
AND t1.animal_id < t2.animal_id
GROUP BY t1.farmer_id,
t1.animal_id,
t1.type
) as t
WHERE RN < 10
and type = 'Sheep'
HAVING COUNT(animal_id) >= 3
DEMO
樣本數據使用
| ANIMAL_ID | FARMER_ID | TYPE |
---------------------------------
| 1 | 1 | dog |
| 2 | 1 | dog |
| 3 | 1 | dog |
| 4 | 1 | dog |
| 5 | 1 | dog |
| 6 | 1 | dog |
| 7 | 1 | dog |
| 8 | 1 | dog |
| 9 | 1 | dog |
| 10 | 1 | dog |
| 11 | 2 | dog |
| 12 | 2 | dog |
| 13 | 2 | dog |
| 14 | 2 | dog |
| 15 | 2 | dog |
| 16 | 2 | dog |
| 17 | 2 | sheep |
| 18 | 2 | sheep |
| 19 | 2 | sheep |
| 20 | 3 | sheep |
| 21 | 3 | sheep |
| 22 | 3 | sheep |
| 23 | 3 | cat |
| 24 | 3 | cat |
| 25 | 3 | cat |
| 26 | 3 | cat |
| 27 | 3 | cat |
| 28 | 3 | cat |
| 29 | 3 | cat |
| 30 | 3 | cat |
結果只有2,因爲即使3只有3只羊ey不在最後10個
這幾乎失控了。對不起,如果我刪除了任何有用的評論 - 那裏有太多的噪音,我從線程中找出任何有建設性的東西。 – BoltClock 2012-07-17 06:09:31