Hi,
The requirements is to get the adjusted itemid for a particular ID.
I have a received items but later on they found out that the itemid is incorrect and they made an adjustment in the records. they make a transaction to change the itemid which they call adjustment entry. which I need to get the recent adjusted itemid for a particular id. the tricky part is I have a multiple receive id from a different receipt date (dt_receipt) which I have hard time on how to do this in script. the only way to differentiate is the actual receipt date per ID. below is the DDL and desired result.
Note:
When they received the id in whse but after sorting they found out the itemid is incorrect then they perform the adjustment entry.
sourceid = 3 --tag as received
sourceid = 7 --tag as adjustment
Declare @sample table
(id nvarchar (35),
sourceid int,
itemid nvarchar(35),
dt_receipt datetime)
insert @sample values ('52164',7,'SOP16GLD','2017-02-10 06:27:57.000')
insert @sample values ('52164',7,'LP16GLD','2016-09-23 03:44:03.000')
insert @sample values ('52164',3,'P16GLD','2016-07-13 03:59:42.000')
insert @sample values ('52060',7,'SOP64GRY','2016-10-18 03:34:33.000')
insert @sample values ('52060',3,'P64GRY','2016-08-27 03:32:10.000')
insert @sample values ('52000',3,'SP64GRY','2017-02-10 06:28:07.000')
insert @sample values ('52001',3,'SP64GRY','2017-06-08 04:36:33.000')
insert @sample values ('52001',3,'SP64GRY','2017-01-27 05:37:10.000')
insert @sample values ('52268',3,'LOP16GLD','2017-06-30 06:27:57.000')
insert @sample values ('52268',7,'LOP16GLD','2017-06-23 03:44:03.000')
insert @sample values ('52268',3,'LP16GLD','2017-05-13 03:59:42.000')
;with cte as
(
select
id, sourceid, itemid, dt_receipt
from @sample
), cte_receive as
(
select
id, sourceid, itemid, dt_receipt
from @sample
where sourceid=3
), cte_adjustment as
(
select
id, sourceid, itemid, dt_receipt
from @sample
where sourceid=7
)
select
d.id, d.sourceid, d.itemid as orig_itemid, s.itemid as new_itemid, d.dt_receipt
from cte_receive d ---receive records
left join cte_adjustment s -- all adjustment records
on s.id = d.id and d.dt_receipt >=s.dt_receipt
where d.sourceid=3 -- all receive records
DESIRED RESULT
id----sourceid---orig_itemid--new_itemid-- dt_receipt
===================================================================
52164---3--------P16GLD-------SOP16GLD------2016-07-13 03:59:42.000
52060---3--------P64GRY-------SOP64GRY------2016-08-27 03:32:10.000
52000---3--------SP64GRY------SP64GRY-------2017-02-10 06:28:07.000
52001---3--------SP64GRY------SP64GRY-------2017-06-08 04:36:33.000
52001---3--------SP64GRY------SP64GRY-------2017-01-27 05:37:10.000
52268---3--------LOP16GLD-----LOP16GLD------2017-06-30 06:27:57.000
52268---3--------LP16GLD------LOP16GLD-------2017-05-13 03:59:42.000