Postgres - 将两个表合并为sum

时间:2017-06-09 09:39:04

标签: sql merge postgresql-9.3

我有两个表格,列数相同,行数不同。我需要将这些表合并为一个使用client_id AND segment_name作为不同条目的唯一标识符,如果两个表之间存在匹配,则将user_count相加。任何帮助非常感谢。

表格A

client_id | segment_name    | user_count
-------------------------------------
45845     | segment45877-58 | 2358
55255     | weather558      | 20
88890     | jobs-listing    | 558

表B

client_id | segment_name | user_count
--------------------------------------
45845     | segment45877-58   | 100 
55255     | weather558        | 350
2454      | leonardo-da-vinci | 5465

表格C(新)

client_id | segment_name      | user_count
-------------------------------------
45845     | segment45877-58   | 2458
55255     | weather558        | 370
88890     | jobs-listing      | 558
2454      | leonardo-da-vinci | 5465

1 个答案:

答案 0 :(得分:1)

你可以尝试

CREATE TABLE C AS  
       (SELECT client_id, 
               segment_name, 
               SUM(user_count) AS user_count
        FROM   (SELECT * FROM A UNION ALL 
                SELECT * FROM B) Data 
        GROUP  BY client_id, segment_name);