所以我有一個這樣的表,其中每個 ID 每行都是唯一的:
表格1
ID data
001 Walter
002 Skylar
003 Hank
004 Marie
我有另一個表,其中 ID 可以多次出現:
表2
ID value
001 apple
001 banana
003 grape
004 graphite
003 jones
001 pear
我想要做的就是給出這兩個表,我想在表 1 中添加一列,以指示ID是否在表 2 中出現多次
最后結果:
ID data table2_multiple
001 Walter 1
002 Skylar 0
003 Hank 1
004 Marie 0
這里我們展示了 bothID = 1和ID = 3have table2_multiple = 1,因為它們在 table2 中都出現了不止一次!
uj5u.com熱心網友回復:
盡管這是一件很奇怪的事情,但您可以這樣做:
update table1
set table2_multiple = case when t.cnt > 1 then 1 else 0 end
from (select ID , count(*) cnt from table2 group by ID) t
where t.id = table1.id
或者,如果您只想選擇:
select t1.* , case when t2.cnt > 1 then 1 else 0 end as table2_multiple
from table1 t1
join (select ID , count(*) cnt from table2 group by ID) t2
on t1.id = t2.id
uj5u.com熱心網友回復:
在所有示例中,我們使用 case 運算式來確定計數是否 >1 設定為 1 否則為 0。
基本聚合函式:
SELECT t1.ID, t1.Data, case when count(*) > 1 then 1 else 0 end as table2_Multiple
FROM Table1 t1 --t1 is an alias of table1
LEFT JOIN table2 t2 --t2 is an alias of table2
ON t1.ID = t2.ID
GROUP BY T1.ID, T1.Data
使用分析函式: (Count() over (partition xxx) 這基本上是說按唯一的 T1ID 和資料對所有記錄進行計數,然后運算式表示如果該計數 > 1 回傳 1 否則為 0。distinct 然后消除所有重復項。
SELECT Distinct t1.ID
, t1.Data
, case when count() over (partition by T1.ID, T1.Data) > 1 then 1 else 0 end as Table_2_multiple
LEFT JOIN Table2 T2
on T1.ID = T2.ID
在這種情況下,使用行內視圖 (T2) 通過 table2 獲取計數,子查詢將只回傳每個 ID 1 行,因此無需處理倍數。
SELECT T1.*, case when coalesce(t2.ValueNo,0) > 1 then 1 else 0 end as table2_Multiple
FROM Table1
LEFT JOIN (SELECT ID, count(*) as valueNo
FROM Table2
GROUP BY ID) T2
on T1.ID = T2.ID
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/383812.html
