根据sql中的重复记录选择和分配值

时间:2014-01-31 01:52:11

标签: sql sql-server tsql ssis lookup

我的数据如下所示:

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

我希望我的输出如下:

输出:如果同一个学生同时在威斯康星州和其他任何州,那么我们需要提到“多重”,当学生只在威斯康星州时,然后提到“国家”,当学生在任何其他状态时提及'不在状态'。此查询需要保留在SSIS查找

Student ID     Status
1             MULTIPLE
2               IN
3               OUT
4               OUT

请告诉我们如何在SQL中实现此输出。

由于

3 个答案:

答案 0 :(得分:0)

一个开始 我不确定第三个 有了工会,你可能不需要明确的

  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

答案 1 :(得分:0)

你需要整理它,但它应该有效

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

答案 2 :(得分:0)

;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