![](/img/trans.png)
[英]SQL Server - Compare on multiple columns in differnet rows within same table
[英]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.