鉴于此数据集:
ID Name City Birthyear
1 Egon Spengler New York 1957
2 Mac Taylor New York 1955
3 Sarah Connor New York 1959
4 Jean-Luc Picard La Barre 2305
5 Ellen Ripley Nostromo 2092
6 James T. Kirk Nostromo 2233
7 Henry Jones La Barre 1899
如何从每个城市只获得2条记录?
答案 0 :(得分:5)
试试这个:
SELECT i1.*
FROM your_table i1
LEFT JOIN your_table i2
ON (i1.City = i2.City AND i1.ID > i2.ID)
GROUP BY i1.ID
HAVING COUNT(*) < 2
ORDER BY city, ID;