# 1.用子查询:SELECT*FROM right2 AS a
WHERE2>(SELECTCOUNT(*)FROM right2 AS b
WHERE b.id = a.id AND b.account > a.account
)ORDERBY a.id, a.account DESC# 2.用exists半连接:SELECT*FROM right2 AS a
WHEREEXISTS(SELECTCOUNT(*)FROM right2 AS b
WHERE b.id = a.id AND a.account < b.account
HAVINGCOUNT(*)<2)ORDERBY a.id, a.account DESC# 同理可以取组内最小的N条记录:SELECT*FROM right2 AS a
WHERE2>(SELECTCOUNT(*)FROM right2 AS b
WHERE b.id = a.id AND b.account < a.account
)ORDERBY a.id, a.account DESC# 用exists:SELECT*FROM right2 AS a
WHEREEXISTS(SELECTCOUNT(*)FROM right2 AS b
WHERE b.id = a.id AND a.account > b.account HAVINGCOUNT(*)<2)ORDERBY a.id, a.account DESC# SQLServer支持top-N:select a.*from tb a where val =(selecttop3 val from tb where name = a.name
)orderby a.name
如果取每组的最大(小)一条记录我常用:
select id, val from t AS b
innerjoin(select*from t AS a
whereorderby val desc) a on a.id = b.id
groupby a.id orderby id;