I don’t know how to word the title properly, anyway what I mean is:
For example I have this ‘transaction’ table
SELECT ITEM_ID, SUM(QUANTITY) AS IN
WHERE TYPE = IN
GROUP BY ITEM_ID
-
SELECT ITEM_ID, SUM(QUANTITY) AS OUT
WHERE TYPE = OUT
GROUP BY ITEM_ID
How do I combine those 2 statements so I can do operation on them?
Thanks
Basically what I want is something like this
SELECT ITEM_ID,
SUM(QUANTITY) where Type = In "Item In",
SUM(Quantity) where Type = Out "Item Out",
Item In - Item Out "Final Qty"
GROUP BY ITEM_ID
6
Answers
You can use IN clause
You want conditional aggregation, i.e. case expressions in the aggregation function:
Another option would be to join the query results:
You can do as using the below queries with OR condition for type / You can use IN condition to get in a single result.
Both will do the same work, just the query condition is different.
Using OR condition:
If we are using the same column then we can use OR condition to fetch the data.
Using IN Condition
How about this
Create a subquery that pivots your rows into columns then
SELECT
from your subquery to find the difference:Result:
db<>fiddle here.
Another option is to use
COUNT
andIF