[英]How to convert a single row table into columns?
我有一个单行查询以这种格式返回数据:
Col1 Col2 Col3 Col4
-----------------------------
1425 3454 2345 3243
我希望它以这种格式显示:
Col1 | 1425
Col2 | 3454
Col3 | 2345
Col4 | 3243
我该怎么做?
我避免使用UNION
方法,因为上面的表是从查询中提取的,并且对于每个<table_name>
我都必须粘贴表查询,这会使过程变慢。
您可以将查询与列名交叉连接,以便在单独的行中显示列值:
select
columns.col,
case columns.col
when 'Col1' then q.col1
when 'Col2' then q.col2
when 'Col3' then q.col3
when 'Col4' then q.col4
end as value
from ( <your query here> ) q
cross join ( values ('Col1'), ('Col2'), ('Col3'), ('Col4') ) as columns(col);
如果每个表的字段数始终保持不变,那么它可能会像这样工作。
DECLARE @Table TABLE(
[Col1] int,
[Col2] int,
[Col3] int,
[Col4] int
)
INSERT INTO @Table VALUES(1425, 3454, 2345, 3243); -- some Test data
SELECT * FROM @Table; -- row
SELECT
p.[Columns],
p.[Value]
FROM (
SELECT
[Col1],
[Col2],
[Col3],
[Col4]
FROM @Table
) x
UNPIVOT(
[Value] FOR [Columns] IN ([Col1],[Col2],[Col3],[Col4]) --
) AS P;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.