首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Sql Group by with transpose

Sql Group by with transpose
EN

Stack Overflow用户
提问于 2020-04-28 20:50:50
回答 1查看 17关注 0票数 0

我真的想不出标题的字眼了。这是我在excel中需要5分钟的事情,但我对SQL还是个新手。

我有一个设备级别的数据集,每个客户可以有许多设备类型,但每种设备类型只能有一种。

我想转换数据,以便它在客户级别进入,并为每个设备提供一组列。

我想我需要从按客户分组开始,但之后我就卡住了。

原始数据

代码语言:javascript
复制
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

新的标头

代码语言:javascript
复制
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

这有意义吗?

EN

回答 1

Stack Overflow用户

发布于 2020-04-28 21:04:20

假设您不需要Dynamic Pivot,条件聚合应该可以做到这一点

代码语言:javascript
复制
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

编辑-只是为了好玩,这里有一个枢轴选项

代码语言:javascript
复制
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

返回

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61480601

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档