你沒有指定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 With Demo
如果再有一個未知數量的值進行改造,那麼你可以使用動態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 with demo
兩者都將產生相同的結果:
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
:
| 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
和PIVOT
功能,那麼你可以在此使用的UNION ALL
組合來UNPIVOT然後CASE
聲明和集合函數來透視複製
請參閱SQL Fiddle with Demo
您使用的是哪種rdbms? – Taryn