我有一张与此类似的表格:
id sml desc amount
1 23 bla 100
2 23 bla 50
3 23 bla 30
4 23 bla 20
1 40 bla1 100
2 40 bla2 23
3 40 bla3 34
4 40 bla4 34
这是其他表的几个连接的结果。我想为每个amount
值选择sml
列中值最高的五名员工。
下面的示例输出:(我的示例中没有五个sml
所以我只使用显示两个。另外,如果第5和第6个值相等,我会喜欢返回两者)
id sml desc amount
1 23 bla 100
2 23 bla 50
1 40 bla1 100
2 40 bla2 100
3 40 bla3 34
我尝试了以下查询:
select [MS_EmployeeNumber],[SA_Semel],[Description],sum([MS_Amount]) as Amount,
rank() over (Partition BY [SA_Semel], [Description]
select [MS_EmployeeNumber],[SA_Semel],[Description],sum([MS_Amount]) as Amount,
rank() over (Partition BY [SA_Semel], [Description]
ORDER BY sum([MS_Amount]) Desc) AS Rank
from [dbo].[MonthlySalary] as sml
inner join [dbo].[SmlAnalyse] as SA on SA.SA_Semel = sml.MS_Semel
inner join [dbo].[SalarySMLlist] as list on list.Semel = SA.SA_Semel
group by [MS_EmployeeNumber],[SA_Semel],[Description]
order by SA_Semel, Amount desc
当我运行这个排名在所有表上完成他的工作并考虑我的要求在MS_Semel上排名。
答案 0 :(得分:0)
我认为您的查询过于复杂。 rank
(或者更确切地说dense_rank
,根据您似乎处理重复的方式)已经为您提供了sml
的排名,现在您只需要相应地进行过滤:
SELECT [id], [sml], [desc], [amount]
FROM (SELECT [id], [sml], [desc], [amount],
DENSE_RANK() OVER (PARTITION BY [sml] ORDER BY [amount] DESC) rk
FROM [dbo].[MonthlySalary]) t
WHERE rk <= 5