Supposing I have this data. How to query this in such a way that will result to this in an efficient way. It will sum the qty of all OUT less the IN per item.
3 Answers
Try this query:
select
"Desc",
sum(case when Type = 'out' then Qty else 0 end) -
sum(case when Type = 'in' then Qty else 0 end)
from yourTable
group by "Desc"
Desc
Note that DESC is a reserved keyword and you should not be naming your databases, tables, or columns using it. I think you would have to escape it in double quotes to get the query to run.
1 Comment
Bigboss
This is exactly what Im looking for. never though CASE WHEN can be used like this.
Or
SELECT Description, SUM(Case WHEN rowtype = 'in' then 1 else -1 end * Qty) as rowqty FROM yourtable GROUP BY description
Note that it is not a good idea to use reserved words as column names. DESC and TYPE are asking for trouble!
1 Comment
Bigboss
yes. I just used that for the purpose of this question.


SUMandGROUP BY.