2012-08-09 46 views
2

表:SQL Server 2008中條件選擇,以輸出多個真值

Date = 20120101, ID = 123456, ParentID = 654321, System1 = 1, System2 = 1 

用戶可活躍System1System2,或二者(1 =真,0 =假)。查詢需要的輸出如下:

System1 System2 
1   0   "System1", "All" 
0   1   "System2", "All" 
1   1   "System1", "System2", "All" 
0   0   "All" 

我試圖case語句,但我無法得到它的輸出我怎麼想。

+0

謝謝@marc_s! – 2012-08-09 19:43:16

回答

1

我知道你想要爲你的數據中的每一行生成多行。

如果是這樣,下面做這個的:

select a.* 
from ((select t.*, 'ALL' as thecode 
     from t 
    ) union all 
     (select t.*, 'System1' 
     from t 
     where system1 = 1 
    ) union all 
     (select t.*, 'System2' 
     from t 
     where system2 = 1 
    ) 
    ) a 
+0

謝謝戈登,這是完美的! – Matt 2012-08-09 19:53:53

2
select *, 
     case when system1 = 1 and system2 = 0 then 'System1, All' 
       when system1 = 1 and system2 = 1 then 'System1, System2, All' 
       when system1 = 0 and system2 = 0 then 'All' 
       when system1 = 0 and system2 = 1 then 'System2, All' 
     end as output 
from your_table