0

我运行 PostgreSQL,我有多个 (10+) 具有相同列名和格式的表,我想对它们的两个列求和。如果其中一个表中缺少一行,我需要将其视为 0 (zero)

两表示例:

表A:

primkey | year | month | day | data_value
--------+------+-------+-----+-----------
20120101| 2012 |  01   |  01 |    3.7
20120102| 2012 |  01   |  02 |    1.0

表B:

primkey | year | month | day | data_value
--------+------+-------+-----+-----------
20120101| 2012 |  01   |  01 |    1.3
20120103| 2012 |  01   |  03 |    5.5

想要的输出:

primkey | year | month | day | data_value
--------+------+-------+-----+-----------
20120101| 2012 |  01   |  01 |    5.0
20120102| 2012 |  01   |  02 |    1.0
20120103| 2012 |  01   |  03 |    5.5

我正在考虑这样做:

SELECT a.primkey, a.year, a.month, a.day, a.data_value+b.data_valueas data_value FROM "TableA" as a FULL JOIN "TableB" as b ON a.primkey = b.primkey;

但它会产生这个(缺少一些 data_values):

primkey | year | month | day | data_value
--------+------+-------+-----+-----------
20120101| 2012 |  01   |  01 |    5.0
20120102| 2012 |  01   |  02 |    
20120103| 2012 |  01   |  03 |   

注意:primkey 是唯一的,并且是 PRIMARY KEY,这需要对加入 10 多个表有效

4

3 回答 3

2
SELECT COALESCE(a.primkey, b.primkey) AS primkey
  , COALESCE(a.year, b.year)          AS year
  , COALESCE(a.month, b.month)        AS month
  , COALESCE(a.day, b.day)            AS day
  , COALESCE(a.data_value,0) + COALESCE( b.data_value, 0) AS data_value
FROM "TableA" AS a
FULL JOIN "TableB" AS b ON a.primkey = b.primkey
   ;
于 2013-02-24T21:22:07.953 回答
1

联合所有表,然后按主键分组。该值的总和将是您正在寻找的结果。

于 2013-02-24T21:17:52.097 回答
1

按照亚伯拉罕的建议,以下是实际代码:

SELECT x.primkey, x.year, x.month, x.day
   , sum(data_value) AS data_value 
FROM 
  (SELECT * FROM "TableA" 
   UNION ALL 
   select * FROM "TableB") 
AS x 
GROUP BY primkey, year, month, day;
于 2013-02-24T22:36:28.403 回答