简体   繁体   中英

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

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:

在此处输入图像描述

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)

在此处输入图像描述

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.

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
group by Client, ProductID, M_POS_TYPE, Amount

Hope you get ahead with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM