对于垃圾标题感到抱歉,但希望这可以解释:
给出表格
name | data
---------------------
1 | 1000
1 | 2000
1 | 3000
2 | 1500
2 | 2500
2 | 3500
我希望能够为数据值排序的所有名称选择顶部(x)。因此,如果x = 2,则返回
name | data
---------------------
1 | 2000
1 | 3000
2 | 2500
2 | 3500
答案 0 :(得分:9)
;with cte AS
(
SELECT name, data, ROW_NUMBER() OVER (PARTITION BY name ORDER BY data DESC) AS RN
FROM YourTable
)
SELECT name, data
FROM cte
WHERE RN<=2
ORDER BY name, data
答案 1 :(得分:2)
稍微通用的方法是(没有看到指定sql server的编辑标签)
Select
name,
data
From
<table> tbl
Where
data In
( Select Top 2 Distinct
data
From
<table>
Where
name = tbl.name
Order By
data Desc
)