简体   繁体   中英

Get the least closest value

I have the following data

Docnum      ItemCode       opnum          startdate         result
73305        Wc-Trim        100          2017-08-18       2017-08-18
73305        WC-Asse        200          2017-11-29       2017-08-18
73305        Wc-id          300          2017-11-30       2017-11-29
73305        wc-qa          400          2017-12-01       2017-11-30

I need to get the output as shown in result column. Explanation: 1.Opnum 100 is the first operation so the date is the same as that of the start date . 2.For opnum 200 it has to get the startdate of opnum 100 3.For opnum 300 it hs to get the startdate of opnum 200 and so on.

NOTE:The opnum are not always in the multiples of 100. with my query i get the startdate of opnum 100 for all the rows.

Query :

select t0.DocNum,t1.itemcode,t1.U_SES_OP_NUM,t1.U_SES_DATESTART
,(select top 1 a0.U_SES_DATESTART from wor1 a0 where 
t1.DocEntry = a0.DocEntry  and a0.ItemType = 290 and
a0.U_SES_OP_NUM < t1.U_SES_OP_NUM)

from OWOR t0inner join WOR1 t1 on t0.DocEntry = t1.DocEntry and t1.ItemType = 290

where t0.docnum = 73305
order by t1.U_SES_OP_NUM

This would usually be done with lag . As MySQL doesn't support it, this can be done with a correlated sub-query.

select t.*,
coalesce((select start_date from tbl
          where docnum=t.docnum and opnum < t.opnum 
          order by opnum desc limit 1)
         ,start_date) as result
from tbl t

The solution assumes there is one row per opnum and docnum.

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