Tsql Unpivot T-sql查询
以下是我查询的结果Tsql Unpivot T-sql查询,tsql,pivot,unpivot,Tsql,Pivot,Unpivot,以下是我查询的结果 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 但我希望查询的输出是 Catego
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
最好的方法是什么?感谢您的帮助。
我尝试取消PIVOT,但未能获得所需的结果。您没有指定RDBMS,但由于您标记了它,我猜是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
组合将其复制到UNPIVOT,然后使用CASE
语句和聚合函数进行PIVOT:
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
请参见谢谢您的快速回复。当我使用第一个查询时,我得到以下错误消息156,级别15,状态1,第30行关键字“FOR”附近的语法不正确。@arvindredy您使用的查询是什么?它似乎在我的小提琴演示中起作用了--@arvindreddy很高兴你让它起作用了。如果StackOverflow上的任何答案有帮助,请确保通过左侧的复选标记向上投票和/或将其标记为已接受。它可以帮助未来的访问者,甚至可以增加你的代表性:)动态查询(第二个)不起作用。有什么想法吗?我也试着在SQL中运行它。这不管用。@arvindreddy你有什么错误吗?你能用失败的版本发布一个sql补丁吗?我的版本似乎起作用了--