我想根据最新购买日期更新相同客户的邮政编码。
Customer_code Postal_code last_purchase_date
12345 444555 20130131
12345 444555 20130131
12345 123456 20110131
由于第三个现场邮政编码已过时,我想更新它并将其替换为最新的邮政编码,即基于最新购买日期的'444555'。因为我有几十万个与此相似的字段,对此有何建议?
答案 0 :(得分:2)
;WITH x AS
(
SELECT Customer_code, Postal_code, rn = ROW_NUMBER() OVER
(PARTITION BY Customer_code ORDER BY last_purchase_date DESC)
FROM dbo.some_table_name
)
UPDATE x SET x.Postal_code = y.Postal_code
FROM x INNER JOIN x AS y
ON x.Customer_code = y.Customer_code
WHERE y.rn = 1 AND x.rn > 1
AND COALESCE(x.Postal_code, '') <> y.Postal_code;
答案 1 :(得分:0)
没有CTE的另一种可能的解决方案:
update tab
set postal_code =
(select top 1 postal_code from tab x where x.customer_code = t.customer_code order by last_purchase_date desc)
from tab t
答案 2 :(得分:0)
请尝试
WITH cte AS
(
SELECT *, rn = ROW_NUMBER() OVER
(PARTITION BY Postal_code ORDER BY Customer_code )
FROM dbo.some_table_name
)
update cte set last_purchase_date='' where rn = 2
根据您的招聘更新。