首页 > 解决方案 > 将垂直数据转换为具有枢轴但没有聚合的水平数据?

问题描述

这是我的数据。我正在尝试将垂直数据转换为水平数据。我尝试使用 PIVOT,但我没有可用作聚合的列。

我不需要使用 PIVOT,但它是我用于这种事情的运算符。我也考虑过,因为我知道所有可能GroupId的 s。

Name      GroupId
Joe       B1
John      B2
Mary      C1
Lisa      D2
Joe       D2

结果将是这样的。我必须连接每个名称的所有字符串:

Name   B1   B2   C1   D2
Joe    B1             D2
John        B2        
Mary             C1
Lisa                  D2

我正在考虑这样的事情,但我知道它不会产生预期的结果。

declare @table table
(
    Name varchar(10),
    GroupId varchar(2)
)

insert into @table
select 'Joe', 'B1' union
select 'John','B2' union
select 'Mary','C1' union
select 'Lisa','D2' union
select 'Joe','D2'

    select *
    from 
    (
      select Name, GroupId
      from @table
    ) src
    pivot
    (
      min(Name)
      for GroupId in ([B1], [B2], [C1], [D2])
    ) piv;

标签: sqlsql-serversql-server-2008tsql

解决方案


You can use conditional aggregation instead

select Name,
       max(case when GroupId = 'B1' then GroupId end) [B1],
       max(case when GroupId = 'B2' then GroupId end) [B2],
       max(case when GroupId = 'C1' then GroupId end) [C1],
       max(case when GroupId = 'D2' then GroupId end) [D2]
from @table t
group by Name;

For your current attempt with pivot operator do aggregation with only one column which is GroupId

select * 
from 
(  
    select Name, GroupId
    from @table
) src pivot (
      max(GroupId)
      for GroupId in ([B1], [B2], [C1], [D2])
 ) piv;

推荐阅读