从SQL中的现有数据扩展行

时间:2017-10-12 18:05:59

标签: sql data-manipulation

我有一个看起来像这样的表:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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查询)的优点是只扫描一次表。