我真的想不出标题的字眼了。这是我在excel中需要5分钟的事情,但我对SQL还是个新手。
我有一个设备级别的数据集,每个客户可以有许多设备类型,但每种设备类型只能有一种。
我想转换数据,以便它在客户级别进入,并为每个设备提供一组列。
我想我需要从按客户分组开始,但之后我就卡住了。
原始数据
Customer - ID - Device - Status - Date
1 - 1 - A - open - 01/10/2020
1 - 2 - B - Closed - 02/10/2020
1 - 3 - C - open - 03/10/2020
2 - 4 - A - open - 01/10/2020
2 - 5 - B - Closed - 02/10/2020
2 - 6 - C - open - 03/10/2020新的标头
Customer - Device A ID - Device A Status - Device A Date - Device B ID - Device B Status - Device B Date - Device C ID - Device C Status - Device C Date这有意义吗?
发布于 2020-04-28 21:04:20
假设您不需要Dynamic Pivot,条件聚合应该可以做到这一点
Select Customer
,[Device A ID] = max(case when Device='A' then ID end)
,[Device A Status] = max(case when Device='A' then [Status] end)
,[Device A Date] = max(case when Device='A' then [Date] end)
,[Device B ID] = max(case when Device='B' then ID end)
,[Device B Status] = max(case when Device='B' then [Status] end)
,[Device B Date] = max(case when Device='B' then [Date] end)
,[Device C ID] = max(case when Device='C' then ID end)
,[Device C Status] = max(case when Device='C' then [Status] end)
,[Device C Date] = max(case when Device='C' then [Date] end)
From YourTable
Group By Customer编辑-只是为了好玩,这里有一个枢轴选项
Select *
From (
Select A.Customer
,B.*
From YourTable A
Cross Apply ( values (concat('Device ',Device,' ID') ,concat('',[ID]) )
,(concat('Device ',Device,' Status'),concat('',[Status]) )
,(concat('Device ',Device,' Date'),concat('',[Date]) )
) B(Item,Value)
) src
Pivot ( max(value) for Item in ( [Device A ID],[Device A Status],[Device A Date],[Device B ID],[Device B Status],[Device B Date],[Device C ID],[Device C Status],[Device C Date] ) ) pvt返回

https://stackoverflow.com/questions/61480601
复制相似问题