簡體   English   中英

聯合二選擇基於某些列(不是整行)刪除重復項

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

我想聯合 2 個選擇語句,結果將是不同的記錄,但是我想在第二個選擇語句中省略重復的結果(考慮一些列)

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類型的項目必須有附加組件

首先 select 獲取專門為 Items 創建的插件列表,table2 為所有 Items 創建一個插件列表,現在如果有一個專門為 Item 創建的插件,將會有一個重復的插件。

嘗試

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

嘗試這個:

;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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM