简体   繁体   中英

How to add the result of two different queries?

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"

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;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM