我需要为一组其他列选择具有最大值的最高记录。在下面的示例数据中,我需要为每组'id','ItemType'
选择最大'权重'的最高记录@Entity
@Table(name = "emp")
public class Employee implements java.io.Serializable { }
预期输出应为
create table sampleTable(id int, ItemType varchar(10), ItemCode varchar(10), Weightage int)
insert into sampleTable values(1, 'A','aaa',2)
insert into sampleTable values(1, 'A','bbb',3)
insert into sampleTable values(1, 'A','ccc',3)
insert into sampleTable values(1, 'B','ddd',1)
insert into sampleTable values(1, 'B','eee',2)
insert into sampleTable values(2, 'A','aaa',1)
我尝试如下
id ItemType ItemCode
--------------------------------
1 A bbb
1 B eee
2 A aaa
但它没有给出预期的结果。感谢
答案 0 :(得分:3)
以下是使用ROW_NUMBER
SELECT TOP 1 WITH ties id,
itemtype,
itemcode
FROM sampletable WITH(nolock)
GROUP BY id,
itemtype,
itemcode,
weightage
ORDER BY Row_number()OVER(partition BY id, itemtype ORDER BY weightage DESC)
TOP 1 with TIES
将根据Order by
希望您知道使用WITH(NOLOCK)
提示的含义。它也会提取未提交的数据
答案 1 :(得分:2)
以下是使用row_number()
的一个选项:
select *
from (
select *, row_number() over (partition by id, itemtype order by Weightage desc) rn
from sampletable
) t
where rn = 1