2

根据以下记录集,我有三列,需要为每组 PersonIds 返回最大 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

谢谢你的帮助!

4

3 回答 3

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
于 2013-08-16T21:27:48.103 回答
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

于 2013-08-17T07:37:52.873 回答
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
于 2013-08-16T21:37:58.543 回答