Union 2选择删除某些列(不是完整行)上的重复项

时间:2014-06-24 10:39:23

标签: sql sql-server

我想结合2个select语句,结果将是不同的记录,但是我想在第二个select语句中省略重复的结果(考虑一些列)

select id,name,[type],[parent] from table1 where [type] = 1 
union
select * from table2 // but exclude results from this table where
                     // a record with the same type and parent exists
                     // in the first select

我已经想过这个(没有经过测试):

select * from(
select *,rank() over(order by [type],[parent]) [rank] from(
  select id,name,[type],[parent] from table1 where [type] = 1 
  union
  select * from table2) t
 ) a where rank = 1

但它似乎不对,有没有更好的方法从第二个选择中排除重复?

编辑:

每个项目都可以有附加组件。和加载项以两种方式创建:

1. table1中特别创建的附加组件 2.公开定义x类型的项必须具有附加组件

首先选择获取专门为Items创建的插件列表,table2为所有Items创建一个附加组件列表,如果有一个专门为其创建的附加组件,将会有一个重复的附加组件项目。

2 个答案:

答案 0 :(得分:1)

select * from table1
union
select * from table2
where not exists(select 1 from table1 
                 where table2.parent = table1.parent 
                 and table2.type = table1.type)

答案 1 :(得分:0)

试试这个:

;WITH cte AS (
   SELECT *, 1 AS SetID FROM table1 WHERE [Type] = 1
   UNION ALL
   SELECT *, 2 AS SetID FROM table2 
)

,cte2 as (
   SELECT *,
   RANK() OVER (PARTITION BY [Type], [Parent] ORDER BY SetID) FROM cte) rk
   FROM cte
)

SELECT * FROM cte2 WHERE rk = 1