sql之分組取組內前幾條資料
阿新 • • 發佈:2018-12-14
一、對分組的記錄取前N條記錄:例如:取每組的前3條最大的記錄
1.用子查詢:
SELECT * FROM tableName a WHERE
(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND b.cnt>a.cnt) < 3
ORDER BY a.id,a.account DESC
where中的select是保證:遍歷所有記錄,取每條記錄與當前記錄做比較,只有當tableName表中同一id不超過3個比當前高時,這條資料才算是排行的前三名。
2.用exists半連線:
SELECT * FROM tableName a WHERE EXISTS
(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND a.account<b.cnt HAVING COUNT(*)<3)
ORDER BY a.id,a.cntDESC
二、同理可以取組內最小的N條記錄:例如:取每組的前3條最小的記錄
1、子查詢
SELECT * FROM tableName a WHERE 3>
(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND b.cnt<a.cnt)
ORDER BY a.id,a.cnt DESC
2、用exists:
SELECT * FROM tableName a WHERE EXISTS
(SELECT COUNT(*) FROM tableName b WHERE b.id=a.id AND a.cnt>b.cnt HAVING COUNT(*)<3)
ORDER BY a.id,a.cnt DESC