Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ItemCode TransactionDate OnHandAfter rn
- Item-123 10/1/2018 960 1
- Item-123 9/28/2018 985 1
- Item-123 9/27/2018 1085 1
- Item-123 9/26/2018 1485 1
- Item-123 9/24/2018 1835 1
- Item-123 9/20/2018 2035 1
- Item-123 9/18/2018 2185 1
- Item-123 9/14/2018 2305 1
- Item-123 9/13/2018 2605 1
- with cte as
- (
- Select TOP 1 * from
- (
- Select
- ItemCode
- ,convert(Date,TransactionDate) TransactionDate
- ,TransactionType
- ,TransactionQuantity
- ,OnHandBefore
- ,OnHandAfter
- ,ROW_NUMBER() over (partition by ItemCode, CONVERT(Date, TransactionDate) order by TransactionDate DESC) as rn
- from InventoryTransaction
- where TransactionType in (1,2,4,8)
- ) as ss
- where rn = 1
- order by TransactionDate DESC
- )
- SELECT
- ab.ExternalId
- ,abdc.[Date]
- ,cte.TransactionDate
- From ABItems ab CROSS JOIN ABDailyCalendar abdc
- FULL OUTER JOIN cte on cte.ItemCode = ab.ExternalId --and cte.TransactionDate <= abdc.[Date]
- Where ab.ExternalID = 'Item-123'
- order by abdc.[Date] DESC
- ExternalId Date TransactionDate
- Item-123 9/30/2018 NULL
- Item-123 9/29/2018 NULL
- Item-123 9/28/2018 NULL
- Item-123 9/27/2018 NULL
- Item-123 9/26/2018 NULL
- Item-123 9/25/2018 NULL
- Item-123 9/24/2018 NULL
- ExternalId Date TransactionDate
- Item-123 9/30/2018 9/28/2018
- Item-123 9/29/2018 9/28/2018
- Item-123 9/28/2018 9/28/2018
- Item-123 9/27/2018 9/27/2018
- Item-123 9/26/2018 9/26/2018
- Item-123 9/25/2018 9/24/2018
- Item-123 9/24/2018 9/24/2018
- SELECT
- itemcode,
- caldate,
- case when caldate = transactiondate then onhandafter else prev_onhandafter end as onhandat,
- case when caldate = transactiondate then 'tran occurred today, using current onhandafter' else 'no tran today, using previous onhandafter' end as reasoning,
- transactiondate,
- onhandafter,
- prev_onhandafter
- FROM
- (
- SELECT
- itemcode,
- transactiondate,
- LAG(transactiondate) over(partition by itemcode order by transactiondate) as prev_transactiondate,
- onhandafter,
- LAG(onhandafter) over(partition by itemcode order by transactiondate) as prev_onhandafter
- FROM
- t
- ) t2
- INNER JOIN
- c
- ON
- c.caldate > t2.prev_transactiondate and c.caldate <= t2.transactiondate
- ORDER BY itemcode, transactiondate
Add Comment
Please, Sign In to add comment