How to select row with max value when duplicate rows exist in SQL Server

前端 未结 4 2012
盖世英雄少女心
盖世英雄少女心 2021-01-01 01:16

I have table like this

DocumentID        | MasterStepID | StepNumber | RoleID | UserID     | Status
JIEP/TT/07/000174 | Approval1    |          1 |   NULL |         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-01 02:13

    You're basically just missing a status comparison since you want one row per status;

    SELECT *
    FROM WF_Approval sr1
    WHERE NOT EXISTS (
        SELECT *
        FROM  WF_Approval sr2 
        WHERE sr1.DocumentID = sr2.DocumentID AND 
              sr1.Status = sr2.Status AND                  # <-- new line
              sr1.StepNumber < sr2.StepNumber
    ) AND MasterStepID = 'Approval1'
    

    or rewritten as a JOIN;

    SELECT *
    FROM WF_Approval sr1
    LEFT JOIN WF_Approval sr2
      ON sr1.DocumentID = sr2.DocumentID 
     AND sr1.Status = sr2.Status
     AND sr1.StepNumber < sr2.StepNumber
    WHERE sr2.DocumentID IS NULL
      AND sr1.MasterStepID = 'Approval1';
    

    SQLfiddle with both versions of the query here.

提交回复
热议问题