如何更新包含重复ID的表的第一行,并使用SQL更新所有唯一ID

时间:2012-07-23 21:55:03

标签: mysql sql

我有一个包含重复项和唯一ID的表。我想在所有交易费用中加10美分,在重复订单的第一行加10美分,例如:

What i start with:
order# Fee    
123    5    
123    4    
111    3
122    5

what I should get: 

order# Fee     
123    5.1    --duplicates
123    4.0    --should not have 10 cents. 
111    3.1
122    5.1

我尝试使用下面的代码,但它会更新每个订单#

-- updates table adds 10 cents to the first order of each duplicate and every unique order
update ebaytemp
set [transaction fees] = [transaction fees] +.10
from (SELECT [order#] 
from ebaytemp
GROUP BY order#
HAVING COUNT(order#) > 1) as E

1 个答案:

答案 0 :(得分:0)

如果您有一个datetimetimestamp列,可以跟踪输入的交易时间(您怎么能不这样做?),您可以将“第一行”作为该列的基础并使用:

UPDATE ebaytemp a
INNER JOIN
(
    SELECT ordernum, MIN(date_entered) AS minentered
    FROM ebaytemp
    GROUP BY ordernum
) b ON a.ordernum = b.ordernum AND a.date_entered = b.minentered
SET a.fee = a.fee + 0.10