sql - 将垂直数据转换为具有枢轴但没有聚合的水平数据?
问题描述
这是我的数据。我正在尝试将垂直数据转换为水平数据。我尝试使用 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;
解决方案
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;
推荐阅读
- delphi - 如何在 delphi 的登录表单中使用 Microsoft Access
- gradle - 为什么gradle找不到资源?
- android - 我想使用 JSON 文件中的数据作为单选按钮的标签(反应原生)
- twitter-bootstrap - 引导滑块 img 大小
- primefaces - 为什么 primefaces 6.2 jar 不向后兼容?
- android - 时序片段转换 - Android
- ldap - 声纳 LDAP 设置
- rust - 无法 tokio::run a boxed Future 因为 trait bound Send 不满足
- java - 无法使用 webdriver 切换到 iframe
- jsf - Primefaces addRow 功能是否与延迟加载数据表兼容?