组合多个结果而不重复

时间:2016-01-21 09:05:42

标签: sql sql-server sql-server-2008 tsql

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

2 个答案:

答案 0 :(得分: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 :(得分: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