SQL垂直分组

时间:2017-05-17 21:29:45

标签: mysql sql relational-database

我有以下RDB表:

ID  Feature
1   1
1   2
2   1
3   1
3   2
3   3

我想要的是以下输出:

ID  Feature1    Feature2    Feature3
1   true        true        false
2   true        false       false
3   true        true        true

实现此目的的最简单的SQL查询是什么?

3 个答案:

答案 0 :(得分:1)

使用cross joinleft join原始表格获取所有功能组合的所有ID,以获得所需的结果。

select i.id,
max(case when f.feature=1 and t.feature is not null then 'true' else 'false' end) as feature1,
max(case when f.feature=2 and t.feature is not null then 'true' else 'false' end) as feature2,
max(case when f.feature=3 and t.feature is not null then 'true' else 'false' end) as feature3
from (select distinct feature from t) f --replace this with the feature table if you have one
cross join (select distinct id from t) i
left join t on t.id=i.id and t.feature=f.feature
group by i.id

如果您只需要布尔值1,0表示True,则可以将查询简化为

select i.id,
max(f.feature=1 and t.feature is not null) as feature1,
max(f.feature=2 and t.feature is not null) as feature2,
max(f.feature=3 and t.feature is not null) as feature3
from (select distinct feature from t) f --replace this with the feature table if you have one
cross join (select distinct id from t) i
left join t on t.id=i.id and t.feature=f.feature
group by i.id

答案 1 :(得分:1)

我相信您需要的只是一个简单的数据透视查询。在这里,我使用布尔值来标记一个特征是否存在(1表示true,0表示false)。

SELECT  f.ID 
      , Feature1    =   SUM(CASE WHEN f.Feature = 1 THEN 1 ELSE 0 END) 
      , Feature2    =   SUM(CASE WHEN f.Feature = 2 THEN 1 ELSE 0 END) 
      , Feature2    =   SUM(CASE WHEN f.Feature = 3 THEN 1 ELSE 0 END) 

FROM    dbo.Features        (NOLOCK)     f

GROUP BY f.ID

答案 2 :(得分:1)

您只需要条件聚合:

select id, max(feature = 1) as feature1, max(feature = 2) as feature2,
       max(feature = 3) as feature3
from t
group by id;

以上返回0和1.如果您确实需要字符串truefalse,则可以执行以下操作:

select id,
       (case when max(feature = 1) then 'true' else 'false' end) as feature1,
       (case when max(feature = 2) then 'true' else 'false' end) as feature2,
       (case when max(feature = 3) then 'true' else 'false' end) as feature3
from t
group by id;