我正在尝试将表格转换为3列
我的示例表就像:
CREATE TABLE tbl1 (A1 int, cA1 int,A2 int, cA2 int,A3 int, cA3 int)
GO
INSERT INTO tbl1 VALUES (60,2,30,3,10,5);
GO
我使用下面的查询从两列获得结果:
select A, value from tbl1
unpivot
(
value
for A in ([A1], [A2],[A3])
) un1;
结果如下:
A | value
--+-------
A1|60
A2|30
A3|10
但我想添加和第二列,结果如下:
A | value1 | value2
--+--------+--------
A1| 60 | 2
A2| 30 | 3
A3| 10 | 5
任何帮助??
答案 0 :(得分:4)
我会使用APPLY
:
select v.*
from tbl1 t cross apply
(values ('A1', t.A1, t.cA1),
('A2', t.A2, t.cA2),
('A3', t.A3, t.cA3)
) v(A, value1, value2);
CROSS APPLY
实现横向连接。这比仅仅透视数据要强大得多,尽管数据的翻转是开始学习横向连接的一种简单方法。
答案 1 :(得分:2)
XML的另一种方式:
DECLARE @x xml = (SELECT * FROM tbl1 as t FOR XML AUTO, TYPE)
;WITH cte AS (
SELECT CAST(t.c.query('local-name(.)') as nvarchar(10)) as [name],
t.c.value('.','int') as [value],
p.number as [pos]
FROM [master]..spt_values p
CROSS APPLY @x.nodes('/t[position()=sql:column("number")]/@*') as t(c)
WHERE p.[type] = 'p'
)
SELECT c.[name] as A,
c.[value] as value1,
c1.[value] as value2
FROM cte c
INNER JOIN cte c1
ON c1.[name] = N'c'+c.[name] and c.pos = c1.pos
输出:
A value1 value2
A1 60 2
A2 30 3
A3 10 5