2017-10-12 56 views
0

我有一個表,看起來像這樣:展開,從現有數據行的SQL

User HasPermA HasPermB HasPermC 
--------------------------------------- 
Joe True  False  True 
Sally True  True  True 

我需要使用SQL將它轉變成以下格式:

User PermissionType 
----------------------- 
Joe   A 
Joe   C 
Sally  A 
Sally  B 
Sally  C 

我會怎麼走關於這樣做?

+2

你正在使用的任何特定的SQL方言?第二個例子是你的數據應該如何存儲在第一位,所以我希望你可以這樣做,作爲修復你的模式的一部分。 – tadman

+1

@tadman - 看到與關鍵問題完全相反的問題(它必須是大量問題的第一個問題)幾乎很有趣,不是嗎? – Twelfth

回答

3

您可以使用UNION ALL:

select * 
from 
(
    select user 
     , case when HasPermA is true then 'A' else null end as PermissionType 
    from table 

    union all 

    select user 
     , case when HasPermB is true then 'B' else null end as PermissionType 
    from table 

    union all 

    select user 
     , case when HasPermC is true then 'C' else null end as PermissionType 
    from table 
) sub 
where sub.PermissionType is not null 
0

一種方法是union all,我會短語:

select user, 'A' as PermissionType from t where HasPermA union all 
select user, 'B' from t where HasPermB union all 
select user, 'C' from t where HasPermC ; 

這是假設你的SQL方言的理解布爾變量。您可能需要諸如HasPermA = 'true'之類的東西。

SQL的幾種方言支持橫向連接 - 使用lateral關鍵字或apply關鍵字(或兩者)。如果是這樣,我想:

select t.user, v.PermissionType 
from t outer apply 
    (value ('A', HasPermA), ('B', HasPermA), ('C', HasPermA)) v(PermissionType, hasPerm) 
where hasPerm; 

使用橫向連接(或unpivot查詢)擁有的僅掃描一次表的優勢。