0

enter image description here

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.

enter image description here

5
  • 2
    What did you try? Commented Jul 6, 2017 at 5:32
  • Hint: Use SUM and GROUP BY. Commented Jul 6, 2017 at 5:34
  • Please read meta.stackoverflow.com/questions/285551/… and the accepted answer Commented Jul 6, 2017 at 5:34
  • @Renzo, I tried doing it manually like ill sum the OUT first and less the IN but doint it will be inefficient I have a lots of data. select (select sum(out) - select sum(in) from table A). Something like this. Commented Jul 6, 2017 at 5:39
  • @Tim Biegelesen yes. But i just don't know how to build it like that Commented Jul 6, 2017 at 5:41

3 Answers 3

3

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.

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

1 Comment

This is exactly what Im looking for. never though CASE WHEN can be used like this.
1
select desc, sum(case Type when 'out' then Qty else -Qty end) from test group by desc;

this will be faster.

Comments

0

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

yes. I just used that for the purpose of this question.

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.