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

在SQL Server 2005中将列显示为行

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

在SQL Server 2005中将列显示为行

为了获得所需的结果,您需要首先提供

UNPIVOT
数据,然后是
PIVOT the
DatePeriod`值。

该UNPIVOT将变换的多列

Transactions
Customers
Visits
为多行。其他答案使用a
UNIOnALL
取消,但是SQL Server 2005
UNPIVOT
是支持该功能的第一年。

要取消数据透视表的查询是:

select dateperiod,  col, valuefrom transactionsunpivot(  value for col in (Transactions, Customers, Visits)) u

参见演示。这会将您当前的列转换为多行,因此数据如下所示:

| DATEPERIOD |          COL | VALUE |-------------------------------------|   Jan 2012 | Transactions |   100 ||   Jan 2012 |    Customers |    50 ||   Jan 2012 |       Visits |   150 ||   Feb 2012 | Transactions |   200 |

现在,由于数据在行中,因此您可以将

PIVOT
函数应用于
DatePeriod
列:

select col, [Jan 2012], [Feb 2012], [Mar 2012]from(  select dateperiod,    t.col, value, c.SortOrder  from  (    select dateperiod,      col, value    from transactions    unpivot    (      value for col in (Transactions, Customers, Visits)    ) u  ) t  inner join  (    select 'Transactions' col, 1 SortOrder    union all    select 'Customers' col, 2 SortOrder    union all    select 'Visits' col, 3 SortOrder   ) c    on t.col = c.col) dpivot(  sum(value)  for dateperiod in ([Jan 2012], [Feb 2012], [Mar 2012])) pivorder by SortOrder;

请参阅带有演示的SQL Fiddle。

如果您有未知的日期期限,那么您将使用动态SQL:

DECLARE @cols AS NVARCHAr(MAX),    @query  AS NVARCHAr(MAX)select @cols = STUFF((SELECT ',' + QUOTENAME(dateperiod)          from transactions         group by dateperiod, PeriodNumberOverall         order by PeriodNumberOverall FOR XML PATH(''), TYPE ).value('.', 'NVARCHAr(MAX)')         ,1,1,'')set @query = 'SELECt col, ' + @cols + '   from   (     select dateperiod,       t.col, value, c.SortOrder     from     (       select dateperiod,         col, value       from transactions       unpivot       (         value for col in (Transactions, Customers, Visits)       ) u     ) t     inner join     (       select ''Transactions'' col, 1 SortOrder       union all       select ''Customers'' col, 2 SortOrder       union all       select ''Visits'' col, 3 SortOrder      ) c       on t.col = c.col ) x pivot  (     sum(value)     for dateperiod in (' + @cols + ') ) p  order by SortOrder'execute(@query)

请参阅带有演示的SQL Fiddle。两者都会给出结果:

|          COL | JAN 2012 | FEB 2012 | MAR 2012 |-------------------------------------------------| Transactions |      100 |      200 |      300 ||    Customers |       50 |      100 |      200 ||       Visits |      150 |      300 |      600 |


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

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

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