Guest User

Untitled

a guest
Oct 23rd, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. ItemCode TransactionDate OnHandAfter rn
  2. Item-123 10/1/2018 960 1
  3. Item-123 9/28/2018 985 1
  4. Item-123 9/27/2018 1085 1
  5. Item-123 9/26/2018 1485 1
  6. Item-123 9/24/2018 1835 1
  7. Item-123 9/20/2018 2035 1
  8. Item-123 9/18/2018 2185 1
  9. Item-123 9/14/2018 2305 1
  10. Item-123 9/13/2018 2605 1
  11.  
  12. with cte as
  13. (
  14. Select TOP 1 * from
  15. (
  16. Select
  17. ItemCode
  18. ,convert(Date,TransactionDate) TransactionDate
  19. ,TransactionType
  20. ,TransactionQuantity
  21. ,OnHandBefore
  22. ,OnHandAfter
  23. ,ROW_NUMBER() over (partition by ItemCode, CONVERT(Date, TransactionDate) order by TransactionDate DESC) as rn
  24. from InventoryTransaction
  25. where TransactionType in (1,2,4,8)
  26. ) as ss
  27. where rn = 1
  28. order by TransactionDate DESC
  29. )
  30. SELECT
  31. ab.ExternalId
  32. ,abdc.[Date]
  33. ,cte.TransactionDate
  34. From ABItems ab CROSS JOIN ABDailyCalendar abdc
  35. FULL OUTER JOIN cte on cte.ItemCode = ab.ExternalId --and cte.TransactionDate <= abdc.[Date]
  36. Where ab.ExternalID = 'Item-123'
  37. order by abdc.[Date] DESC
  38.  
  39. ExternalId Date TransactionDate
  40. Item-123 9/30/2018 NULL
  41. Item-123 9/29/2018 NULL
  42. Item-123 9/28/2018 NULL
  43. Item-123 9/27/2018 NULL
  44. Item-123 9/26/2018 NULL
  45. Item-123 9/25/2018 NULL
  46. Item-123 9/24/2018 NULL
  47.  
  48. ExternalId Date TransactionDate
  49. Item-123 9/30/2018 9/28/2018
  50. Item-123 9/29/2018 9/28/2018
  51. Item-123 9/28/2018 9/28/2018
  52. Item-123 9/27/2018 9/27/2018
  53. Item-123 9/26/2018 9/26/2018
  54. Item-123 9/25/2018 9/24/2018
  55. Item-123 9/24/2018 9/24/2018
  56.  
  57. SELECT
  58. itemcode,
  59. caldate,
  60. case when caldate = transactiondate then onhandafter else prev_onhandafter end as onhandat,
  61. case when caldate = transactiondate then 'tran occurred today, using current onhandafter' else 'no tran today, using previous onhandafter' end as reasoning,
  62. transactiondate,
  63. onhandafter,
  64. prev_onhandafter
  65.  
  66. FROM
  67. (
  68. SELECT
  69. itemcode,
  70. transactiondate,
  71. LAG(transactiondate) over(partition by itemcode order by transactiondate) as prev_transactiondate,
  72. onhandafter,
  73. LAG(onhandafter) over(partition by itemcode order by transactiondate) as prev_onhandafter
  74. FROM
  75. t
  76. ) t2
  77. INNER JOIN
  78. c
  79. ON
  80. c.caldate > t2.prev_transactiondate and c.caldate <= t2.transactiondate
  81. ORDER BY itemcode, transactiondate
Add Comment
Please, Sign In to add comment