I have two different tables and I want to get these two different output in single result. Here I want to display the result of both queries in single report.
Query 1
Select name, sum(purchasqty)-sum (soldqty) as pending
from (select p.name, p.qty as purchasqty, s.qty as soldqty
from purchase p
left join sold s on p.id = s.id )
group by name;
Query 2
Select name, sum(qty) as damage
from purchase p
where con = 'c'
group by name
This will do
Select name, sum(purchasqty)-sum (soldqty) as pending, '' as damage
from (select p.name, p.qty as purchasqty, s.qty as soldqty
from purchase p
left join sold s on p.id = s.id )
group by name
union all
Select name, '' as pending, sum(qty) as damage
from purchase p
where con = 'c'
group by name
This is a little tricky because you seem to be aggregating at a level different from what you are joining on. I would recommend:
select p.name, (p.purchasqty - coalesce(ps.soldqty, 0) as pending ,
p.damage
from (select p.name, sum(qty) as purchase_qty,
sum(case when con = 'c' then qty else 0 end) as damage
from purchase p
group by p.name
) p left join
(select p.name, sum(s.qty) as soldqty
from purchase p join
sold s
on p.id = s.id
group by p.name
) ps
on ps.name = p.name;
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.