从两个不同的表中添加两列

时间:2014-01-15 16:30:42

标签: sql oracle

我有两个具有相同字段类型的表。这里常见的字段是* BG_ID *和商店编号。现在我想从两个表中 SUM 两列(* total_area *和* total_area_blk *)并按BG_ID对它们进行分组。

以下是我尝试过的不起作用:

 select t.bg_id, t.store_number,sum(a.total_area),sum(b.total_area_blk)
 from (select bg_id,store_number,total_area
 from temp_Prop_area_block a
 where store_number='33665'
 union all
 select bg_id,store_number,total_area_blk 
 from temp_Prop_area_BG b
 where store_number='33665')

1 个答案:

答案 0 :(得分:3)

希望,这对你有帮助!

SELECT bg_id,  store_number,  SUM(total_area)
FROM
  (
    SELECT bg_id,  store_number,  total_area as total_area
    FROM temp_Prop_area_block a
    WHERE store_number='33665'
    UNION ALL
    SELECT bg_id,   store_number,  total_area_blk as total_area
    FROM temp_Prop_area_BG b
    WHERE store_number='33665'
  ) my_view
GROUP BY bg_id, store_number;