我需要帮助尝试更新具有多个重复记录的表,但我被卡住了。
我有此表,我需要使用im_cust9
值更新alt_item_id1
。
我用来从表中获得此结果的查询如下:
SELECT
o.item_id, o.alt_item_id1, o.im_cust9, o.owner_id, o.if_updatestamp
FROM
item_master o
INNER JOIN
(SELECT
alt_item_id1, COUNT(*) AS dupeCount
FROM
item_master
WHERE
owner_id = 'GIII' AND alt_item_id1 <> ''
GROUP BY
alt_item_id1
HAVING
COUNT(*) > 1) oc ON o.alt_item_id1 = oc.alt_item_id1
WHERE
owner_id = 'GIII' AND o.alt_item_id1 <> ''
ORDER BY
alt_item_id1, if_updatestamp ASC
不确定如何更新每组重复的最旧记录alt_item_id1
我正在使用SQL Server 2012
非常感谢任何帮助!
答案 0 :(得分:1)
要获取要更新的最新行,请使用 if_updatestamp 的最大值。对于最古老的使用最小。然后将它连接到你的表中为udpate这样......
update IM
Set IM.im_cust9 = NewDupeRow.alt_item_id1
From item_master IM
JOIN (
SELECT alt_item_id1,Max(if_updatestamp) MaxUpdateValue
FROM item_master WHERE owner_id='GIII' AND alt_item_id1<>''
GROUP BY alt_item_id1 ) NewDupeRow
On IM.alt_item_ID = NewDupeRow.alt_item_ID
AND IM.if_updatedstamp = NewDupeRow.MaxUpdateValue
答案 1 :(得分:1)
您可以使用可更新的CTE和row_number()
:
with toupdate as (
select i.*,
row_number() over (partition by alt_item_id order by if_updatestamp) as seqnum
from item_master i
)
update toupdate
set im_cust9 = alt_item_id1
where seqnum = 1;