合并来自2个表的SUM

时间:2016-09-06 07:18:26

标签: mysql

我有以下2个MYSQL周表:

TableA_Wk1

Id | Price
----------
1  | 1
1  | 2
2  | 5

TableA_Wk2

Id | Price
----------
1  | 2
4  | 2

我可以将价格分组到一个表格中:

SELECT Id, SUM(Price) FROM TableA_Wk1
GROUP BY Id

并获取

Id | Price
----------
1  | 3
2  | 5

我还想考虑TableA_Wk2表来获得以下内容:

Id | Price
----------
1  | 5
2  | 5
4  | 2

如果我使用UNION ALL,结果将被分开:

SELECT Id, SUM(Price) FROM TableA_Wk1
  GROUP BY Id
UNION ALL
SELECT Id, SUM(Price) FROM TableA_Wk2
  GROUP BY Id

3 个答案:

答案 0 :(得分:1)

联合结果集,然后执行求和以得到求和值。

select sum(price) from (
   select price from TableA_Wk1
   union all  
   select price from TableA_Wk1
) as alais

答案 1 :(得分:1)

首先从这两个表中获取所有<Id,price>个元组。然后在结果表上使用SUMGROUP BY Id

SELECT 
t.Id,
SUM(t.price) 
FROM 
(
 SELECT Id, Price FROM TableA_Wk1
 UNION ALL
 SELECT Id, Price FROM TableA_Wk2
) AS t
GROUP BY t.Id

注意

UNION删除重复项。

UNION ALL没有。

答案 2 :(得分:1)

首先UNION,然后是GROUP BY

SELECT t.id,sum(t.price) as price
FROM (
      SELECT id,price from TableA_Wk1
      UNION ALL
      SELECT id,price from TableA_Wk2
     ) t
GROUP BY t.id