Home > Mobile >  Add new column based on conditions and the value difference of other column
Add new column based on conditions and the value difference of other column

Time:07-25

I think I might be overlooking something obvious here. I'm not asking someone to write the whole code for me, I just need a hint or a link to a similar case.

My query:

select Client , ProductID, M_POS_TYPE AS Keep_or_Keep_in_Transit, Amount
FROM inventory_table inv_table
JOIN inventory_position inv_pos
ON inv_pos.ProductID=inv_table.ProductID
group by Client, ProductID, M_POS_TYPE, Amount

Output:

enter image description here

How can I add a new column that checks if the the subtraction of the values in the column: Amount is different from 0 for same ProductID and Client?

Desired:

5-4<>0  

THEN

(Y)

enter image description here

What I have tried to use is conditionals, CASE statement, but how can I make sure it will calculate the difference for the same Client and ProductID?

I'm looking for a solution in the generic case, there are thousands of different ProductsIDs and Clients values in the table. I'm a bit stuck in this problem.

CodePudding user response:

because you only asked for a tip or hint. Without example or test with data and only as short explanation. Google for "Analytic Functions" that could help you to solve it. So you can sum up per client, ProductID and then compare in a CASE.

Maybe something like this.

select Client , ProductID, M_POS_TYPE AS Keep_or_Keep_in_Transit, Amount,
sum(case when M_POS_TYPE = 'Keep_Transit' then AMOUNT*-1 else AMOUNT end) over (partition by Client, ProductID) as DIFF
FROM inventory_table inv_table
JOIN inventory_position inv_pos
ON inv_pos.ProductID=inv_table.ProductID

Hope you get ahead with it.

  • Related