您没有指定 RDBMS,但由于您将其标记为tsql,我猜是 sql-server。这实际上是一个UNPIVOT
,然后是一个PIVOT
。如果您知道需要转换的值,则可以通过静态版本对它们进行硬编码:
select *
from
(
select year_month, value, category
from table1
unpivot
(
value
for category in (cat1_per, cat2_per, cat3_per, cat4_per)
) un
) x
pivot
(
max(value)
for year_month in ([2004_06], [2005_10])
)p
请参阅带有演示的 SQL Fiddle
如果您有未知数量的值要转换,那么您可以使用动态 sql 数据透视表:
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('Table1') and
C.name like 'cat%per'
for xml path('')), 1, 1, '')
select @colsPivot = STUFF((SELECT ','
+ quotename(t.year_month)
from Table1 t
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select year_month, value, category
from table1
unpivot
(
value
for category in ('+ @colsunpivot +')
) un
) x
pivot
(
max(value)
for year_month in ('+ @colspivot +')
) p'
exec(@query)
请参阅带有演示的 SQL Fiddle
两者都会产生相同的结果:
| CATEGORY | 2004_06 | 2005_10 |
--------------------------------
| cat1_per | 0.892 | 0.79 |
| cat2_per | 0.778 | 0.629 |
| cat3_per | 0.467 | 0.581 |
| cat4_per | 0.871 | 0.978 |
如果由于某种原因,您没有UNPIVOT
andPIVOT
函数,那么您可以使用UNION ALL
to unpivot 的组合,然后使用CASE
语句和聚合函数来复制它:
select category,
max(case when year_month = '2004_06' then value end) [2004_06],
max(case when year_month = '2005_10' then value end) [2005_10]
from
(
select year_month, cat1_per value, 'cat1_per' category
from table1
union all
select year_month, cat2_per value, 'cat2_per' category
from table1
union all
select year_month, cat3_per value, 'cat3_per' category
from table1
union all
select year_month, cat4_per value, 'cat4_per' category
from table1
) un
group by category
请参阅带有演示的 SQL Fiddle