2016-01-21 49 views
1

enter image description here合併多個結果,而無需重複

我嘗試下面的查詢,但我得到重複行,我想這兩個結果的額外行應標明空。

WITH E_CTE (Column1,Column2,Column3)AS 
(Select Column1,Column2,Column3 From Table1 as c1) 
Select x.*,y.* 
from (SELECT * from E_CTE Where column3='Yes') as x, 
     (SELECT * FROM E_CTE Where column3='No') as y 
+1

可是你爲什麼要這麼做? !? yes行和no行之間是否有任何關係? – jarlh

+1

你還沒有解釋爲什麼或如何將第1行鏈接到第3行 –

+0

它們之間沒有任何聯繫它只是表示問題 – Rohan

回答

1

使用窗口函數ROW_NUMBER和有條件的聚合:

WITH cte AS (
    SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY Column3 ORDER BY Column1) 
    FROM #Table1 
) 
SELECT Column1Yes = MAX(CASE WHEN Column3 = 'yes' THEN Column1 END), 
     Column2Yes = MAX(CASE WHEN Column3 = 'yes' THEN Column2 END), 
     Column1No = MAX(CASE WHEN Column3 = 'no' THEN Column1 END), 
     Column2No = MAX(CASE WHEN Column3 = 'no' THEN Column2 END) 
FROM cte 
GROUP BY rn; 

LiveDemo

輸出:

╔════════════╦════════════╦═══════════╦═══════════╗ 
║ Column1Yes ║ Column2Yes ║ Column1No ║ Column2No ║ 
╠════════════╬════════════╬═══════════╬═══════════╣ 
║   1 ║ A   ║   3 ║ C   ║ 
║   2 ║ B   ║   4 ║ D   ║ 
║   ║   ║   5 ║ E   ║ 
╚════════════╩════════════╩═══════════╩═══════════╝ 
1

而另一種解決方案是使用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