Question

My data looks as below:

Student_ID   State
1             WI
1             IL
1             IL
2             WI
3             IL
4             IL
4             MN

I want my Output to be as follows:

Ouput: If the same student is in both WI and any other state then we need to mention as 'multiple', when student is only in WI then mention as 'InState' and When the student is in any other state mention as 'OUT of STATE'. This query needs to be kept in SSIS lookup

Student ID     Status
1             MULTIPLE
2               IN
3               OUT
4               OUT

Please let me know how can we achieve this output in SQL.

Thanks

Was it helpful?

Solution

You'll need to tidy it up but it should work

WITH x AS
-- eliminate all duplicates,set up a counter for each distinct record
-- as well as flag for WI
(SELECT DISTINCT studentID, STATE, 1 AS cnt, CASE WHEN STATE = 'WI' THEN 1 ELSE 0 END WI
 FROM DataTable)
SELECT studentID, 
CASE 
    WHEN MAX(wi) = 0 THEN 'OUT' -- this student is not in WI at all
    WHEN MAX(wi) = 1 AND SUM(cnt) > 1 THEN 'MULTI' -- this student is in WI as well as another state
    WHEN MAX(wi) = 1 AND SUM(cnt) = 1 THEN 'IN' END AS Status  -- this student is in WI and and no other state
FROM x GROUP BY studentID

OTHER TIPS

;WITH CTE AS
(  
    SELECT DISTINCT SID, [State],
        Score = 
            CASE 
            WHEN [State] = 'WI' THEN 100
            ELSE 1
            END
    FROM T
)

SELECT SID, 
    Status = 
    CASE
        WHEN SUM(Score) > 100 THEN 'MULTIPLE'
        WHEN SUM(Score) = 100 THEN 'IN'
        ELSE 'OUT'
        END
 FROM CTE
 GROUP BY SID

A start
I am not sure about the third
And with a union you may not need distinct

  select distinct T1.ID, 'multiple' 
    from table T1 
    join table T2 
      on T1.ID = T2.ID
     and T1.State  = 'WI'
     and T2.State != 'WI'
union 
  select distinct T1.ID, 'in' 
    from table T1 
    left outer join table T2 
      on T1.ID = T2.ID
     and T1.State  = 'WI'
     and T2.State != 'WI'
   where T2.ID is null
union
 select distinct T1.ID, 'out' 
    from table T1 
    left outer join table T2 
      on T1.ID = T2.ID
     and T1.State != 'WI'
     and T2.State  = 'WI'
   where T2.ID is null
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top