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

前端 未结 4 1987
盖世英雄少女心
盖世英雄少女心 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 01:50

    Try This

    SELECT T1.* FROM WF_Approval T1 
    JOIN
    (SELECT DISTINCT [Status], DocumentID, MAX(StepNumber) as [StepNumber] from WF_Approval 
    GROUP BY DocumentID, [Status])  T2 
    ON T1.DocumentID = T2.DocumentID AND T1.[Status] = T2.[Status]
    AND T1.StepNumber = T2.StepNumber
    ORDER BY StepNumber ASC, Status ASC
    


    OUTPUT:

    JIEP/TT/07/000174   Approval1   1   NULL    0006100022  1
    JIEP/TT/07/000174   Approval1   5   18      0006100022  3
    JIEP/TT/07/000174   Approval1   6   16      0006104115  6
    
    0 讨论(0)
  • 2021-01-01 01:55

    The simple table (Student_Course) currently is like this with duplicate records assume:

    Sname   Sid
    ------------
    Ravi    S001
    Ravi    S001
    Jack    S002
    Jack    S002
    Jack    S002
    Guru    S003
    Smith   S004
    Arun    S005
    Rajeev  S006
    

    Query:

    SELECT S.Sid, S.Sname, Count(*) As Occurance
    FROM Student_Course AS S
    GROUP BY S.Sid
    HAVING Count(S.Sid) > 1
    Order By Count(*) Desc Limit 1
    

    Output:

    Sid     Sname   Occurance
    -------------------------
    S002    Jack    3
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 02:16

    This should be faster than a self-join because (most probably) only a single scan over the table is required.

    select DocumentID, 
           MasterStepID, 
           StepNumber, 
           RoleID,
           UserID , 
           Status
    from (
        select wf.*
               row_number() over (partition by wf.status order by wf.stepnumber desc) as rn
        from  WF_Approval wf
    ) t
    where rn = 1
    order by StepNumber
    
    0 讨论(0)
提交回复
热议问题