以下是我的查询结果
Year_Month.........cat1_per......cat2_per........cat3_per......cat4_per
2004_06...............0.892..........0.778............0.467..........0.871
2005_10...............0.790..........0.629............0.581..........0.978
但我希望我的查询输出为
Category...........2004_06..............2005_10
cat1_per.............0.892..................0.790
cat2_per.............0.778..................0.629
cat3_per.............0.467..................0.581
cat4_per.............0.871..................0.978
最好的方法是什么?任何帮助表示赞赏。 我试过Unpivot但是没能得到理想的结果。
答案 0 :(得分:2)
您没有指定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 pivot:
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)
两者都会产生相同的结果:
| 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
组合来解除此操作,然后再将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