繁体   English   中英

用最早的更新第一行,使用第二个更新第二行,依此类推

[英]Update first row with oldest, the next with second oldest, and so forth

我无法在没有关系的SQL Server中编写更新。 我浏览了整个论坛,但很难找到答案。

如果客户数量匹配,我需要更新OCR。 问题在于这不是唯一的密钥。 因此,如果来自客户的一条记录多于一笔金额组合,我需要在查找表中使用最旧的匹配项并从中更新OCR。 然后,我需要使用第二个最旧的文件,并使用其OCR更新第二行。

我试图在下表中对其进行可视化。

欢迎提出所有建议!

要更新的表-更新之前

Customer       OCR  Amount      
740000010417        220.000     
740000010417        220.000     
740000010421        300.000     
740000010421        250.000     

查找表

Customer         OCR            Amount  Date                    ID
740000010417    222357110626    220.000 2011-11-11 15:48:48.510 100642
740000010417    222350553822    220.000 2011-10-18 10:10:26.210 18680
740000010417    222350464525    220.000 2011-10-18 10:10:26.210 18681
740000010417    222357110725    220.000 2011-11-11 15:48:48.510 102547
740000010421    222357127726    250.000 2011-11-11 15:48:48.510 102548
740000010421    222357127725    220.000 2011-10-19 10:10:26.210 102549
740000010421    222357130555    250.000 2011-10-19 10:10:26.210 102550

更新后的表格

Customer            OCR          Amount     
740000010417    222350553822    220.000     
740000010417    222350464525    220.000     
740000010421                    300.000     
740000010421    222357130555    250.000 
update table set ocr = 

(select l.ocr
from 
(select l.customer as customer, l.ocr as ocr, l.amount as amount, l.date as date, ROW_NUMBER() OVER (partition by l.customer, l.amount Order BY l.date) as RowNum
from lookuptable l
order by l.date
)a

(select t.customer as customer, t.amount as amount, ROW_NUMBER() OVER (PARTITION BY t.customer, t.amount order by t.customer) as RowNum
from table t
)b
where a.customer = b.customer and a.amount=b.amount and a. rowNum = b.RowNum
)

我没有测试过,但是它可能会给您一个想法。

编辑:刚刚意识到不需要加入内部查询。 想法是首先从查找表中选择所有记录,然后按日期的升序分配它们的行号。 因此相同的客户和相同的金额以及不同的日期将获得递增顺序的行号。

然后从旧表中获取记录,并根据客户和金额分配行号。 这样,我们可以匹配客户,金额和行号,因为第一个相同的客户和金额将被初始化为最早的OCR,因为按日期对行进行排序

这就是我最终的魅力所在! 感谢Zohaib!

UPDATE   t1
SET    t1.ocr = l1.ocr    
FROM    ( SELECT    *
              , rnk = ROW_NUMBER() OVER ( PARTITION BY t.customer,
                                          t.Amount ORDER BY t.customer, t.Amount )
           FROM      table t) t1
        LEFT JOIN 
    ( SELECT    *
              , rnk = ROW_NUMBER() OVER ( PARTITION BY l.customer,
                                          l.Amount ORDER BY l.date, l.id)
          FROM      lookuptable l) l1

      ON t1.id = l1.id
        AND t1.Amount = l1.amount
        AND t1.rnk = l1.rnk

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM