Reputation: 13
I am making a query using the union method, I would like to add one of my fields that have the same segment but with different costs.
Example:
Select Segment, costs From tableA
union all
Select Segment, costs From tableb
Result
Segment | costs
---------------
Seg 1 | 1000
seg 2 | 2000
Seg 3 | 3000
Seg 1 | -200
Seg 3 | -300
The result I want:
Segment | costs
---------------
Seg 1 | 800
seg 2 | 2000
Seg 3 | 2700
I am currently using a query with many join methods, but I would like to have an idea of how to solve this problem with the "union all"
Upvotes: 0
Views: 58
Reputation: 665
Use Aggregator Function, like
SELECT Segment, SUM(Cost)Cost FROM
(Select Segment, costs From tableA
UNION ALL
Select Segment, costs From tableb)A
GROUP BY Segment
You can use union all to append results from two independent but same column size and type result set, and later you can sum your field to get the unique result;
Upvotes: 1