我在SQL中有以下表
AL1 | AL2 | AL3 | ACB | LL1 | LL2 | LL3 | LCB
------------------------------------------------
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
我想将其转换为
| L1 | L2 | L3 | CB
-----------------------------
A | 1 | 2 | 3 | 4
L | 5 | 6 | 7 | 8
任何帮助都将不胜感激。
答案 0 :(得分:4)
您可以选择不同的查询,并使用UNION
SELECT 'A' AS COL, AL1, AL2, AL3, ACB
FROM TBL
UNION
SELECT 'L' AS COL, LL1, LL2, LL3, LCB
FROM TBL;
输出:
| COL | AL1 | AL2 | AL3 | ACB |
-------------------------------
| A | 1 | 2 | 3 | 4 |
| L | 5 | 6 | 7 | 8 |
答案 1 :(得分:3)
试试这个 -
<强> 查询: 强>
DECLARE @temp TABLE
(
AL1 INT, AL2 INT, AL3 INT, ACB INT,
LL1 INT, LL2 INT, LL3 INT, LCB INT
)
INSERT INTO @temp (AL1, AL2, AL3, ACB, LL1, LL2, LL3, LCB)
VALUES (1, 2, 3, 4, 5, 6, 7, 8)
SELECT
COL
, COL1 = CASE WHEN COL = 'A' THEN AL1 ELSE LL1 END
, COL2 = CASE WHEN COL = 'A' THEN AL2 ELSE LL2 END
, COL3 = CASE WHEN COL = 'A' THEN AL3 ELSE LL3 END
, COL4 = CASE WHEN COL = 'A' THEN ACB ELSE LCB END
FROM @temp
CROSS JOIN (VALUES ('A'), ('L')) AS t(COL)
<强> 输出: 强>
COL COL1 COL2 COL3 COL4
---- ----------- ----------- ----------- -----------
A 1 2 3 4
L 5 6 7 8
执行计划:
答案 2 :(得分:3)
另一种方式(与Devart相同的计划,但更简洁的语法)
SELECT V.*
FROM TBL
CROSS APPLY (VALUES ('A', AL1,AL2,AL3,ACB),
('L', LL1,LL2,LL3,LCB)) V( COL, LL1, LL2, LL3, LCB)
答案 3 :(得分:0)
DECLARE @test AS TABLE(int1 INT, int2 INT, int3 INT, int4 INT)
INSERT INTO @test
( int1, int2, int3, int4 )
VALUES ( 1, -- int1 - int
2, -- int2 - int
3, -- int3 - int
4 -- int4 - int
)
SELECT * FROM @test
SELECT COL FROM @test
CROSS APPLY (VALUES (int1), (int2), (int3), (int4)) t(COL)
查看此示例。