Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union two selects removing duplicates base on some columns (not the full row)

Tags:

sql

sql-server

I want to union 2 select statements that the result will be distinct record-wise however I want to omit duplicate results in second select statement (considering some columns)

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

I have thought of this (not tested):

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

but it doesn't seem right, is there a better way to exclude duplicate from second select?

Edit:

each item can have add-ons. and add-ons are created in 2 ways:

1.specifically created add-ons in table1

2.publicly defining that an item of type x must have add-on

first select gets the list of addons that are specifically created for the Items , table2 create a list of add-ons for all the Items now there will be a duplicate add-on if there were an add-on specifically created for an Item.

like image 936
Ashkan Mobayen Khiabani Avatar asked Jun 24 '14 10:06

Ashkan Mobayen Khiabani


2 Answers

try

select * from table1
union
select * from table2
where not exists(select 1 from table1 
                 where table2.parent = table1.parent 
                 and table2.type = table1.type)
like image 133
T I Avatar answered Oct 16 '22 10:10

T I


try this:

;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 
like image 26
g2server Avatar answered Oct 16 '22 10:10

g2server