栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在sql中创建查询以透视数据?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在sql中创建查询以透视数据?

此数据转换称为A

PIVOT
,从SQL Server 2005开始,具有将数据从行转换为列的功能。

有多种方法可以完成此操作,具体取决于您是否有要转换为列的静态数量的值。所有这些都涉及向

row_number()
数据添加a
,因此您可以返回任何产品的多行。

您可以将聚合函数与

CASE
表达式一起使用:

select   max(case when product = 'x' then detail end) x,  max(case when product = 'y' then detail end) y,  max(case when product = 'z' then detail end) zfrom(  select p.product, d.detail,    row_number() over(partition by p.product order by p.slno) rn  from product p  inner join detail d    on p.product = d.product) srcgroup by rn

参见带有演示的SQL Fiddle

您可以使用以下

PIVOT
功能:

select x, y, zfrom(  select p.product, d.detail,    row_number() over(partition by p.product order by p.slno) rn  from product p  inner join detail d    on p.product = d.product) srcpivot(  max(detail)  for product in (x, y, z)) piv

请参阅带有演示的SQL Fiddle。

如果您有未知数量的值(在这种情况下为产品)要转换为列,那么您将要使用动态SQL:

DECLARE @cols AS NVARCHAr(MAX),    @query  AS NVARCHAr(MAX)select @cols = STUFF((SELECT distinct ',' + QUOTENAME(product)          from product FOR XML PATH(''), TYPE ).value('.', 'NVARCHAr(MAX)')         ,1,1,'')set @query = 'SELECt ' + @cols + ' from   (     select p.product, d.detail,       row_number() over(partition by p.product order by p.slno) rn     from product p     inner join detail d       on p.product = d.product ) x pivot  (     max(detail)     for product in (' + @cols + ') ) p 'execute(@query)

参见带有演示的SQL Fiddle

所有查询的结果是:

|    X |      Y |      Z |--------------------------| good |    bad |  worse ||  bad | (null) | (null) |


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596706.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号