我有一个巨大的表,因此我需要根据其他2列中的值更新一列上的值,然后提取数据并将其放在其他新的#temp表中 代码段数据的格式如下
DOC_GUID NAME Value Timestamp
-------- ---- ----- ---------
1111 V1 AC 1134
1111 V2 AB 1134
1112 V1 N 1234
1112 V2 AB 1234
1113 V1 AC 1334
1113 V2 N 1334
1114 V1 N 1434
1114 V2 N 1434
我需要更新值使其变为
DOC_GUID NAME Value Timestamp
-------- ---- ----- ---------
1111 V1 AC 1134
1111 V2 AC 1134
1112 V1 AB 1234
1112 V2 AB 1234
1113 V1 AC 1334
1113 V2 AC 1334
1114 V1 N 1434
1114 V2 N 1434
我试图写出如下逻辑,但是根本无法执行
UPDATE #temp
SET Value = CASE WHEN (A.DOC_GUID = B.DOC_GUID
FROM #temp A inner join #temp B
ON A.Value= 'AC' OR
B.Value = 'AC')
THEN 'AC'
WHEN (A.DOC_GUID = B.DOC_GUID
FROM #temp A inner join #temp B
ON A.Value= 'AB' OR
B.Value = 'AB')
THEN 'AB' END
答案 0 :(得分:2)
DDL:
declare @tbl table (DOC_GUID int, NAME varchar(3), Value varchar(3), Timestamp int );
insert into @tbl values
(1111,'V1','AC',1134),
(1111,'V2','AB',1134),
(1112,'V1','AB',1234),
(1112,'V2','N',1234),
(1113,'V1','AC',1334),
(1113,'V2','N',1334),
(1114,'V1','N',1434),
(1114,'V2','N',1434);
更新查询:
update t1 set t1.Value = t2.Value
from @tbl t1 join (
select *,
-- here I use case statement to make AC come before AB
row_number() over (partition by DOC_GUID order by case when [Value] = 'AC' then 'AA' else [Value] end) rn
from @tbl
) t2 on t1.DOC_GUID = t2.DOC_GUID
where t2.rn = 1
答案 1 :(得分:1)
您可以使用窗口功能和可更新的CTE进行此操作:
with toupdate as (
select t.*,
max(case when seqnum = 1 then value end) over (partition by doc_guid) as use_value
from (select t.*,
row_number() over (partition by doc_guid order by priority) as seqnum
from t left join
(values ('AC', 1),
('AB', 2),
('N', 3)
) v(value, priority)
on v.value = t.value
) t
)
update toupdate
set value = use_value
where use_value <> value;
这种方法有两个主要优点。
首先,更改优先级非常简单,因为这些优先级嵌入在VALUES()
子句中。
第二,外部where
子句仅更新需要更新的行。
这也应该具有良好的性能特征。
答案 2 :(得分:0)
我们可以尝试将CASE
和EXISTS
子句一起使用:
UPDATE t1
SET Value = CASE WHEN EXISTS (SELECT 1 FROM #temp t2
WHERE t1.DOC_GUID = t2.DOC_GUID AND
t2.Value = 'AC')
THEN 'AC'
WHEN EXISTS (SELECT 1 FROM #temp t2
WHERE t1.DOC_GUID = t2.DOC_GUID AND
t2.Value = 'AB')
THEN 'AB'
ELSE 'N' END
FROM #temp t1;