而另一種解決方案是使用FULL JOIN
這樣的 -
模式
DECLARE @T TABLE (Column1 int, Column2 VARCHAR(10), Column3 VARCHAR(10));
INSERT @T
VALUES (1, 'A', 'YES'), (2, 'B', 'YES'), (3, 'C', 'NO'), (4, 'D', 'NO'), (5, 'E', 'NO');
查詢
;WITH E_CTE
AS
( SELECT
Column1
,Column2
,Column3
,rn = ROW_NUMBER() OVER (PARTITION BY c1.Column3 ORDER BY c1.Column1)
FROM @T AS c1
)
SELECT
Column1Yes
,Column2Yes
,Column1No
,Column2No
FROM (SELECT
Column1 AS Column1Yes
,Column2 AS Column2Yes
,rn
FROM E_CTE
WHERE column3 = 'Yes') AS x
FULL JOIN (SELECT
Column1 AS Column1No
,Column2 AS Column2No
,rn
FROM E_CTE
WHERE column3 = 'No') AS y
ON x.rn = y.rn
輸出
Column1Yes Column2Yes Column1No Column2No
1 A 3 C
2 B 4 D
NULL NULL 5 E
可是你爲什麼要這麼做? !? yes行和no行之間是否有任何關係? – jarlh
你還沒有解釋爲什麼或如何將第1行鏈接到第3行 –
它們之間沒有任何聯繫它只是表示問題 – Rohan