Search code examples
sql-servercasedistincthaving

distinct(varchar) and having clauses within SQL Server CASE statement


SELECT
    CASE 
       WHEN Max([Status]) = 'COMPLETED' 
          THEN 'COMPLETED'
       WHEN MAX([Status]) != 'COMPLETED' 
            AND (DENSE_RANK() OVER (PARTITION BY Branch, Place ORDER BY [priority])) < 4 
          THEN 'CURRENT'
       ELSE 'INCOMPLETE' 
    END AS [STATUS]
FROM 
    TEMP_JOB

My data is like this, I am trying this in SQL Server

Branch  Place   Item    Status
------|------|-------|--------------------
B1      P1      I1      COMPLETE
B1      P1      I1      COMPLETE
B1      P1      I2      COMPLETE
B1      P1      I2      COMPLETE
B1      P1      I2      INPROGRESS
B1      P1      I3      INPROGRESS
B1      P1      I3      INPROGRESS

I need data to be consolidated as following. For each branch and place if all items with same item number are complete then status should be Complete, if at least one item line is InProgress then status should display as INPROGRESS

Branch  Place   Item    Status
------|-------|-------|--------------------
B1      P1      I1      COMPLETE
B1      P1      I2      INPROGRESS
B1      P1      I3      INPROGRESS

I have tried multiple case statements but the result is not correct.

enter image description here


Solution

  • From the same data and expected results, the following query works:

    SELECT Branch,Place,Item,
      CASE WHEN COUNT(DISTINCT Status) =1 THEN MAX(Status)
        ELSE N'INPROGRESS'
      END AS [Status]
    FROM TEMP_JOB
    GROUP BY Branch,Place,Item;