我正在使用union方法进行查询,我想添加一个具有相同细分但成本不同的字段。
示例:
Select Segment, costs From tableA
union all
Select Segment, costs From tableb
结果
Segment | costs
---------------
Seg 1 | 1000
seg 2 | 2000
Seg 3 | 3000
Seg 1 | -200
Seg 3 | -300
我想要的结果
Segment | costs
---------------
Seg 1 | 800
seg 2 | 2000
Seg 3 | 2700
我目前正在使用具有许多联接方法的查询,但是我想对如何使用“全部联盟”解决这个问题有个想法
答案 0 :(得分:1)
使用聚合器功能,例如
SELECT Segment, SUM(Cost)Cost FROM
(Select Segment, costs From tableA
UNION ALL
Select Segment, costs From tableb)A
GROUP BY Segment
您可以使用union all来追加两个独立但相同的列大小和类型结果集的结果,然后可以对字段求和以获得唯一结果;