我使用以下查询来选择用户最高资格,但我得到重复的值。因为用户有多个资格。
SELECT hrQualifications.Qualification,hrUserQualifications.HRUserID,MAX(hrQualifications.QualificationLevel) as Qlevel
FROM hrQualifications RIGHT OUTER JOIN
hrUserQualifications ON hrQualifications.QualificationID = hrUserQualifications.QualificationID RIGHT OUTER JOIN
hrUserApplyforPositions ON hrUserQualifications.HRUserID = hrUserApplyforPositions.HRUserID
WHERE (hrUserApplyforPositions.HrPositionID = 1)
group by hrQualifications.Qualification,hrUserQualifications.HRUserID
我得到的输出
Qualification UserID QualificationLevel
B.Sc.(Hons) 12 16
F.Sc 12 12
B.Sc.(Hons) 18 16
需要输出。我想要最高的用户资格。
Qualification UserID QualificationLevel
B.Sc.(Hons) 12 16
B.Sc.(Hons) 18 16
答案 0 :(得分:1)
执行所需操作的好方法是使用row_number()
。这会向行添加一个序列号,在分区内重新开始并按另一个字段排序。
查询:
with t as (
SELECT q.Qualification, uq.HRUserID, q.QualificationLevel as Qlevel,
row_number() over (partition by uq.HRUserID
order by q.QualificationLevel desc
) seqnum
FROM hrQualifications q RIGHT OUTER JOIN
hrUserQualifications uq
ON q.QualificationID = uq.QualificationID RIGHT OUTER JOIN
hrUserApplyforPositions uap
ON uq.HRUserID = uap.HRUserID
WHERE uap.HrPositionID = 1
)
select *
from t
where seqnum = 1;
请注意,我还添加了表别名以使查询更具可读性。