用0替换重复值的第二个实例

时间:2014-11-06 16:16:52

标签: sql-server

我有数据记录,再次基于一些表和计算,我的输出看起来像

ItemCode    LineTotalSum1   ShippingExpenseCode TotalShippingAmt
Item_O      9140.5           10                 13.24
Item_O      9140.5           13                 6.62
Item_O      9140.5           6                  744
Item_P      9099             10 <- 0 here       13.24
Item_P      9099             6  <- 0 here       744

现在我想将列ShippingExpenseCode上的第二个重复值替换为0,我应该在SQL脚本上写什么?

2 个答案:

答案 0 :(得分:1)

如果重复项由前三列CardCodeDocPostingDateItemCode确定:

WITH CTE AS
(
    SELECT CNT = COUNT(*) OVER (PARTITION BY CardCode, DocPostingDate, ItemCode), *
    FROM dbo.TableName t
)
UPDATE CTE SET ShippingExpenseCode = 0
WHERE CNT > 1

答案 1 :(得分:0)

我得到了脚本,使用以下脚本将所有第二个或更大的实例替换为0。

Update T1 Set T1.TotalShippingAmt = 0,TotalShippingVAT = 0
from dbo.Table
where Row <> (Select MIN(Row) from dbo.Table T2 
    where    
        T2.ShippingExpenseCode = T1.ShippingExpenseCode And 
        T2.CardCode = T1.CardCode And T2.DocPostingDate = T1.DocPostingDate)