how to find out max of a field for two different conditions in sql

前端 未结 2 741
野的像风
野的像风 2021-01-26 12:36

I have a table EMPDATA with the following data:

EntityId    MeetDate    SourceCode  Status
1           06.11.2017   AB          FNL
1           05.2.2018    AB           


        
2条回答
  •  醉梦人生
    2021-01-26 13:23

    You can easily achieve the expected output using conditional aggregation:

    SELECT EntityId,
           MAX(CASE 
                  WHEN SourceCode = 'AB' AND status = 'FNL' THEN MeetDate 
               END) AS LastDate,
           MAX(CASE WHEN SourceCode = 'IU' THEN MeetDate END) AS InterimDate          
    FROM mytable
    GROUP BY EntityId
    

    This query implements all logic described in the OP except for:

    • InterimDate ... which has occurred after the latest Meetdate for SourceCode ‘AB’ and Status ‘FNL’.

    You can implement this using a CTE so that the code looks cleaner:

    ;WITH CTE AS (
    SELECT EntityId,
           MAX(CASE 
                  WHEN SourceCode = 'AB' AND status = 'FNL' THEN MeetDate 
               END) AS LastDate,
           MAX(CASE WHEN SourceCode = 'IU' THEN MeetDate END) AS InterimDate          
    FROM mytable
    GROUP BY EntityId
    )
    SELECT LastDate, 
           CASE 
              WHEN InterimDate > LastDate THEN InterimDate
           END AS InterimDate
    FROM CTE 
    

    Demo here

提交回复
热议问题