Reputation: 629
I have to queries on which I am applying a union function.
select item, loc, qty from rms_transfer
union
select item, loc, qty from sim_transfer
wherever item and loc are same in both the queries, the qty of both the queries should add up in in the final result.
How do we achieve that ?
Upvotes: 2
Views: 1814
Reputation: 1269463
I think you want union all
, not union
:
select item, loc, qty from rms_transfer;
union all
select item, loc, qty from sim_transfer;
union
removes duplicates. So, if you want to keep all the original rows, then use union all
.
If you want the values on the same row, then you can use a post-aggregation:
select item, loc, sum(qty)
from (select item, loc, qty from rms_transfer;
union all
select item, loc, qty from sim_transfer
) il
group by item, loc
Upvotes: 4
Reputation: 72165
Just do a GROUP BY
:
SELECT item, loc, SUM(qty) AS qty
FROM (
SELECT item, loc, qty FROM rms_transfer
union
SELECT item, loc, qty FROM sim_transfer) AS t
GROUP BY item, loc
Same item, loc
pairs will be grouped together and their corresponding quantities will be summed up.
Upvotes: 2