I am trying to write a query that will select two different result from table.
Let us suppose that following is table sale:
Supp items
A 1
A 1
A 3
A -1 //negative represent return item
B 1
I want to select sum of sale products and returned products. So the following will be the result:
Supp Sale Return
A 5 1
B 1 0
I am trying following query but not getting desired results
select
t.Supp, count(t.items)'Quantity', count(s.items)'ReturnedQuantity'
from sale t, sale s
where t.items='1' and s.items='-1'
group by
t.supp,s.supp
order by
sum(cast(t.items as int)) desc
Will somebody tell me what will be query to get this result?
What was wrong with the original query:
First, you use
COUNT()when you should useSUM().Second you join two instances of table
sale. This might have worked if you had usedt.items >0 AND s.items < 0But it would be more complex and you would need alsot.supp = s.supp. Unneccecarily complexity (and it may not even work even then).Third, the
where t.items='1' and s.items='-1'conditions does not sum any rows with items different than1or-1. And you obsiously have some different, like the3.