简体   繁体   中英

Update Column if Null from previous values

I am using DB2 SQL. I have a table name ITEMATRIX which looks like -

ITNBR   LBRCST  MFGOH   STDUC   YRMNT
RM-013         0    0   499.6   2010-02
H-178          0    0   164.5   2010-02
FP9-003        0    0   6       2010-02
FP9-059        0    0   2       2010-02
A94-103B-M     0    0   0       2010-02
140-07-1012C   0    0   10      2010-05
140-07-1012C   0    0   0       2010-06

then

 ITNBR  LBRCST  MFGOH   STDUC   YRMNT
 140-07-1012C   0   0   10      2010-05
 140-07-1012C   0   0   **10**      2010-06

etc etc......

I want to update the STDUC field if the value is 0 or Null to value present to the nearest month. Lets say for ItNBR 140-07-1012C the STDUC is 0 for 2010-05 , then first I have to find if that Item Number has a standard cost in the year 2010 for any month, if yes then copy the value of the last month which is 2010-04 to it. There are many records with the same Item number which I am transposing later. Can anyone give me some ideas of how to go about this?

Thanks Varun

I think he following is the logic that you want:

update itematrix
    set stduc = (select stduc
                 from itematrix im2
                 where im2.stduc <> 0 and im2.stduc is not null and im2.itnbr = itematrix.itnbr
                 order by yrmnt desc
                 fetch first 1 row only
                )
    where stduc is null or stduc = 0

I haven't tested this in DB2. There may be a problem using fetch first on the same table as the one used in the update. I find the documentation ambiguous.

If you don't need an actual update, but just want to see the value, then try:

select itemmatrix.*,
       (select stduc
        from itematrix im2
        where im2.stduc <> 0 and im2.stduc is not null and im2.itnbr = itematrix.itnbr
        order by yrmnt desc
        fetch first 1 row only
       )
from itemmatrix

我将流程转移到EXCEL,并且可以从最早的月份开始对单个成本值使用IFVLOOKUP轻松完成,然后简单地比较上个月的值并进行相应的更改,然后使用&创建UPDATE语句。我将流程转移到EXCEL并可以使用IFVLOOKUP轻松实现,然后使用&创建UPDATE语句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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