Quantcast
Channel: Questions in topic: "ms sql"
Viewing all articles
Browse latest Browse all 16

SQL Query to forward last month current bal to Balance last month of next month

$
0
0
Guys, I have 3 data tables to consolidate and calculate the balance_cm(current month) and balance_lm(last month) and Order Qty. I want to add the result of balance_cm and balance_lm and Order qty as column. Also the balance_cm of previous month would be my balance_lm of next month. Thank you for help in advance.... Please see below DDL and desired result. Formula Order Qty: CASE WHEN (t1.oemneedqty - (t1.OnHandqty + onorderqty)- ISNULL(t2.balance_lm,0)) <0 THEN 0 ELSE (t1.oemneedqty - (t1.OnHandqty + onorderqty)- ISNULL(t2.balance_lm,0)) END AS Order_Qty, Balance_CM formula: CASE WHEN (t1.oemneedqty - (t1.OnHandqty + onorderqty)- ISNULL(t2.balance_lm,0)) >= 0 THEN 0 ELSE (t1.oemneedqty - (t1.OnHandqty + onorderqty)- ISNULL(t2.balance_lm,0)) * -1 END AS balance_cm My Query select oe.po_month, oe.item, oe.x_oemneedqty as oemneedqty ,sum(case when oh.a_onhandqty is null then 0 else oh.a_onhandqty end) as OnHandqty ,sum(case when op.b_onorderqty is null then 0 else op.b_onorderqty end) as onorderqty ,SUBSTRING(CAST(CONVERT(date,DATEADD(month,1,CONVERT(datetime,SUBSTRING(oe.po_month,1,4)+SUBSTRING(oe.po_month,6,2)+'01'))) AS VARCHAR),1,7) AS po_month_before ,SUBSTRING(CAST(CONVERT(date,DATEADD(month,+1,CONVERT(datetime,SUBSTRING(oe.po_month,1,4)+SUBSTRING(oe.po_month,6,2)+'01'))) AS VARCHAR),1,7) AS po_month_curr FROM #oemneed oe LEFT OUTER join #onhand oh on oe.po_month= oh.oh_month LEFT OUTER join #openorder op on oe.po_month= op.delivery_month GROUP BY oe.po_month ,oe.item ,oe.x_oemneedqty Sample Desired Result: let say po_month '2019-08' balance_lm = 0 po_month----item---oemneedqty---OnHandqty--onorderqty----Order_Qty balance_cm balance_lm 2016-09-----A1003----1000---------900--------600------------0----------500---------0 2016-10-----A1003----2000---------600--------0------------900----------0----------500 2016-11-----A1003----1000---------500--------200----------300----------0-----------0 2016-12-----A1003----1000---------500--------600-----------0-----------100 --------0 2017-01-----A1003----1000---------500-------1200-----------0-----------800--------100

Viewing all articles
Browse latest Browse all 16

Trending Articles