2

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 ?

4
  • Sample data and desired results would clarify what you want to do. Commented Feb 15, 2016 at 14:18
  • grouping worked! and its giving correct result. Commented Feb 15, 2016 at 14:19
  • There is a general flaw in using 'union' here, because it skips rows from the second query that are already part of the first one. You have to use a 'union all' for this. The needed grouping is already mentioned within the answers so I skip it here. Commented Feb 15, 2016 at 14:26
  • Are item + loc unique in the two tables or can I find several rows for an item + loc in one of the tables? Commented Feb 15, 2016 at 14:32

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

union will remove duplicate rows between the two tables. So they won't be counted twice which is - I think - what Imran wants
Great answer and combined with union all instead of simple union, solved my challenge.

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.