要获得结果,您需要做的是一个两步的过程,分别实现函数UNPIVOT
和PIVOT
函数。
第一步是UNPIVOT
数据,这需要您的多个列M1
,M2
等,并将它们转换为具有值和列名的两列:
select zone, value, col
from data
unpivot
(
value
for col in ([M1], [M2], [M3],
[M4], [M5], [M6], [M7])
) unpiv;
请参阅带有演示的 SQL Fiddle
执行完UNPIVOT
之后,您可以将 应用于PIVOT
列Zone
:
select *
from
(
select zone, value, col
from data
unpivot
(
value
for col in ([M1], [M2], [M3],
[M4], [M5], [M6], [M7])
) unpiv
) src
pivot
(
sum(value)
for zone in ([North], [South], [West], [East], [Central])
) piv;
请参阅带有演示的 SQL Fiddle
现在,如果您无权访问PIVOT
andUNPIVOT
函数,则可以使用 a UNION ALL
for theUNPIVOT
和带有 a 的聚合函数CASE
来复制PIVOT
:
select col,
sum(case when zone='North' then value end) North,
sum(case when zone='South' then value end) South,
sum(case when zone='West' then value end) West,
sum(case when zone='East' then value end) East,
sum(case when zone='Central' then value end) Central
from
(
select zone, M1 value, 'M1' col
from data
union all
select zone, M2 value, 'M2' col
from data
union all
select zone, M3 value, 'M3' col
from data
union all
select zone, M4 value, 'M4' col
from data
union all
select zone, M5 value, 'M5' col
from data
union all
select zone, M6 value, 'M6' col
from data
union all
select zone, M7 value, 'M7' col
from data
) un
group by col
请参阅带有演示的 SQL Fiddle
最后,如果您有未知数量的列要取消转置或转置,那么您可以使用它的动态版本:
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsUnpivot = stuff((select ','+quotename(C.name)
from sys.columns as C
where C.object_id = object_id('data') and
C.name not in ('zone')
for xml path('')), 1, 1, '')
select @colsPivot = STUFF((SELECT distinct ','
+ quotename(Zone)
from data
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select zone, value, col
from data
unpivot
(
value
for col in ('+ @colsunpivot +')
) u
) unpiv
pivot
(
max(value)
for zone in ('+ @colspivot +')
) p'
exec(@query)
请参阅带有演示的 SQL Fiddle
所有版本都将产生相同的结果。
结果:
| COL | CENTRAL | EAST | NORTH | SOUTH | WEST |
-------------------------------------------------
| M1 | 6233 | 3944 | 6233 | 12440 | 33736 |
| M2 | 3636 | 14584 | 17743 | 20017 | 30532 |
| M3 | 2 | 2 | 2 | 7 | 5 |
| M4 | 6233 | 728 | 6233 | 8057 | 2184 |
| M5 | 6717 | 953 | 6717 | 9724 | 2056 |
| M6 | 6825 | 970 | 7369 | 13418 | 1944 |
| M7 | 6825 | 970 | 7369 | 13418 | 1944 |