簡體   English   中英

SQL 將表的行與多列進行比較

[英]SQL Compare rows of a table with multiple columns

我有一張桌子 T1

ID Col1 Col2 活躍
1 T1 v1 1
2 T2 v2 0

現在收到以下數據,需要將其插入到上表中。

|  Col1  |  Col2  |  
|--------|--------|
|   T1   |   v1   |
|   T2   |   v2   |
|   T3   |   v3   |   

由於此數據包含一些重復值,因此需要根據 IsActive Column 值插入。 對於帶有 IsActive 1 的行,需要使用 IsActive 2 插入,對於帶有 IsActive 0 的行,需要使用 IsActive 1 插入,如下所示,需要使用 IsActive 1 插入唯一數據,現在這不是問題

ID Col1 Col2 活躍
1 T1 v1 1
2 T2 v2 0
3 T1 v1 2
4 T2 v2 1
5 T3 v3 1

我創建了一個臨時表 #Temp 並在新傳入數據和現有表中的數據中插入了常用行,如下所示:

#溫度

Col1 Col2 活躍
T1 v1 1
T2 v2 0
T1 v1 NULL
T2 v2 NULL

使用 Group By 我可以 select 重復行,但我需要根據 IsActive 值插入,所以我卡在這里。

insert into T1
select Col1, Col2, '1' from #Temp
GROUP BY Col1, Col2
HAVING COUNT(Col1) > 1

我需要以上部分的幫助,在此先感謝

Try this:
    
-- create temp table with values to be inserted
INSERT INTO #ToInsert
    ([Col1], [Col2])
VALUES
    ('T1', 'v1'),
    ('T2', 'v2'),
    ('T3', 'v3')

-- join each value of the temp table to the original table. if
-- value exists increment its `IsActive` by 1, otherwise set it to 1
INSERT INTO t (Col1, Col2, IsActive)
SELECT i.Col1, i.Col2, COALESCE(t.IsActive + 1, 1) AS IsActive
FROM #ToInsert i
LEFT JOIN (
   SELECT Col1, Col2, max(IsActive) as IsActive
   FROM t 
   GROUP BY Col1, Col2
) t ON i.Col1 = t.Col1 AND i.Col2 = t.Col2

演示在這里

暫無
暫無

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

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