1

I have data in two tables as below

Table 1 :

Material |Ordr Qty 
---------|---------
abcd     |4253

Table 2 :

Material | Stck Qty 
---------|---------
abcd     |1000
abcd     |2000
abcd     |2000

Expected Output :

Material |Ordr Qty |Stck Qty |Column D
---------|---------|---------|---------
abcd     |4253     |1000     |3253
abcd     |4253     |2000     |1253
abcd     |4253     |2000     |-747

Logic for column D is like

4253-1000 = 3253
3253-2000 = 1253
1253-2000 = -747

LAG(ordr qty - stck qty,1,0)over (ORDER BY material)-stck qty

I am trying above LAG function and getting below output

abcd    4253    1000    -1000
abcd    4253    2000    1253
abcd    4253    2000    253

Let me know how to achieve the expected output.

1 Answer 1

1

Consider a window sum() rather than lag():

select t1.*, t2.stck_qty,
    t1.ordr_qty - sum(t2.stck_qty) over(partition by material order by t2.id)
from t1
inner join t2 using(material)
order by material, t2.id

To get a stable result, you need a column that defines the ordering of the rows in t2: I assumed id.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.