根据以下记录集,我有三列,需要为每组PersonId返回最大CaseId值。
ID PersonId CaseId
66 30 410
1681 30 3508
226 31 958
856 31 2213
1023 31 2400
例如,我想返回一个记录集,例如:
ID PersonId CaseId
1681 30 3508
1023 31 2400
如您所见,我总是为所有PersonId集返回最大CaseId。
我尝试了以下内容,但并不总是返回最大记录:
WITH latestRecord AS
(
SELECT CaseId, PersonId, ID,
ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY ID ASC) AS RN
FROM Employee
)
SELECT Max(RN),CaseId, PersonId
FROM latestRecord
GROUP BY RN,CaseId, PersonId
--WHERE RN > 1
ORDER BY CaseId
感谢您的帮助!
答案 0 :(得分:3)
你几乎没错:
WITH latestRecord
AS
(
SELECT CaseId,
PersonId,
ID,
RN=ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY CaseId DESC)
FROM Employee
)
SELECT CaseId,
PersonId,
ID
FROM latestRecord
WHERE RN = 1
ORDER BY CaseId
答案 1 :(得分:1)
您还可以使用子查询查找每组PersonId的最大CaseId值。
SELECT *
FROM dbo.Employee t
JOIN (
SELECT PersonId, MAX(CaseId) AS CaseId
FROM dbo.Employee
GROUP BY PersonId
) t2 ON t.PersonId = t2.PersonId AND t.CaseId = t2.CaseId
为了提高性能,请使用以下索引:
CREATE INDEX x ON dbo.Employee(PersonId, CaseId) INCLUDE(ID)
请参阅SQLFiddle
答案 2 :(得分:0)
这样的事可能吗?
SELECT EMP.ID, DRVDTBL.PERSONID, DRVDTBL.CaseId FROM
(select max(PERSONID) as PERSONID, CaseId from Employee
group by CaseId) AS DRVDTBL
INNER JOIN Employee EMP ON DRVDTBL.PERSONID=EMP.PERSONID