SQL联合并根据优先级删除重复项

时间:2013-11-21 01:08:11

标签: sql sql-server

请看下面的SQLFiddle
http://sqlfiddle.com/#!2/5dd713/2/0

我有两张桌子。我将两个表联合起来以获取我正在寻找的数据 但我想删除重复项并使用table1中的信息作为优先级

目前该表看起来像这样(info1来自table1,info2来自table2)

1, info1
2, info1
3, info1
3, info2
4, info1
4, info2
5, info1
5, info2
6, info2
7, info2

所以最终结果如下所示

1, info1
2, info1
3, info1
4, info1
5, info1
6, info2
7, info2

我该怎么做?

谢谢

2 个答案:

答案 0 :(得分:2)

我使用两个工会解决了这个请求:

-- fully functional example using your provided data.
DECLARE @table1 TABLE (ID INT, Value NVARCHAR(20))
DECLARE @table2 TABLE (ID INT, Value NVARCHAR(20))

SET NOCOUNT ON;
INSERT @table1 VALUES (1, 'info1');
INSERT @table1 VALUES (2, 'info1');
INSERT @table1 VALUES (3, 'info1');
INSERT @table2 VALUES (3, 'info2');
INSERT @table1 VALUES (4, 'info1');
INSERT @table2 VALUES (4, 'info2');
INSERT @table1 VALUES (5, 'info1');
INSERT @table2 VALUES (5, 'info2');
INSERT @table2 VALUES (6, 'info2');
INSERT @table2 VALUES (7, 'info2');
SET NOCOUNT OFF;

-- this is not the most efficient way to go, I did this to show the steps involved to obtain your desired result
-- a more efficient solution follows.
SELECT T.ID, T.Value FROM (

    -- only appear in table1
    SELECT * FROM @table1 WHERE ID NOT IN (SELECT ID FROM @table2)

    -- appear in both table, but choose element from table1
    UNION ALL
    SELECT * FROM @table1 WHERE ID IN (SELECT ID FROM @table2)

    -- only appear in table 2
    UNION ALL
    SELECT * FROM @table2 WHERE ID NOT IN (SELECT ID FROM @table1)

) T 
ORDER BY T.ID

-- if you prefer more efficiency and without a UNION, try this:
SELECT
     CASE WHEN A.ID IS NOT NULL THEN A.ID ELSE B.ID END AS ID
     ,CASE WHEN A.Value IS NOT NULL THEN A.Value ELSE B.Value END AS Value

FROM @table1 A
    FULL OUTER JOIN @table2 B ON A.ID=B.ID;

答案 1 :(得分:0)

我认为你使用UNION / UNION ALL来获取这两个表的结果,我想你可以做这样的事情

;WITH CTE (ID , Info, rn)
AS(
  SELECT * ,  ROW_NUMBER() OVER (PARTITION BY  ID, INFO_Col1 ORDER BY ID ASC) 
  FROM (    
  SELECT ID, INFO_Col1 FROM table_1
  UNION ALL
  SELECT ID, INFO_Col2 FROM Table_2)Query
  )
  SELECT Info1, Info2 
  FROM CTE
  WHERE  rn = 1