【问题标题】:Merge tables with PostgreSQL使用 PostgreSQL 合并表
【发布时间】:2017-11-17 15:58:30
【问题描述】:

这个问题的标题不准确,但我不知道如何总结。如果可以,请随时重新编写!

这是两个表格的摘录:

table_a

code  | year   | nb_a
------+--------+------
  A1  |   2017 |    1      
  A2  |   2012 |    2
  A3  |   2014 |    2

table_b

code  | year   | nb_b
------+--------+------
  A1  |   2013 |    1
  A1  |   2014 |    1
  A2  |   2012 |    1

我需要合并这些表才能得到这个输出:

code  | year   | nb_a | nb_b | total
------+--------+------+------+-------
  A1  |   2013 |    0 |    1 |     1
  A1  |   2014 |    0 |    1 |     1
  A1  |   2017 |    1 |    0 |     1
  A2  |   2012 |    2 |    1 |     3
  A3  |   2014 |    2 |    0 |     2

我找不到正确的查询。我需要类似下面的东西(我知道它不起作用)但是如何将所有代码和年份合并到一个表中,因为代码和年份在两个表中都没有重复......

SELECT 
  code,
  "year",
  table_a.nb_a,
  table_b.nb_b,
  table_a.nb_a + table_b.nb_b AS total

FROM table_a, table_b
WHERE table_a.code = table_b.code;

以下是快速创建上述表格的 SQL 脚本:

CREATE TABLE public.table_a (code TEXT, "year" INTEGER, nb_a INTEGER);
CREATE TABLE public.table_b (code TEXT, "year" INTEGER, nb_b INTEGER);

INSERT INTO public.table_a (code, "year", nb_a) VALUES (A1, 2017, 1), (A2, 2012, 2), (A3, 2014, 2);
INSERT INTO public.table_b (code, "year", nb_b) VALUES (A1, 2013, 1), (A1, 2014, 1), (A2, 2012, 1);

【问题讨论】:

  • 为什么 2012 有一行而 2012,2013,2017 - 三个?..
  • 不确定是否理解您的问题...代码是地理区域代码,而不是 ID。
  • 我猜对了吗?..你想要一个完整的外部连接?..

标签: sql postgresql merge postgresql-9.4


【解决方案1】:

你可能是looking for FULL OUTER JOIN

SELECT
  coalesce(a.code,b.code),
  coalesce(a."year",b.year),
  coalesce(a.nb_a,0),
  coalesce(b.nb_b,0),
  coalesce(a.nb_a,0) + coalesce(b.nb_b,0) AS total
FROM table_a a full outer join table_b b on a.code = b.code and a.year = b.year;
 coalesce | coalesce | coalesce | coalesce | total
----------+----------+----------+----------+-------
        1 |     2013 |        0 |        1 |     1
        1 |     2014 |        0 |        1 |     1
        1 |     2017 |        1 |        0 |     1
        2 |     2012 |        2 |        1 |     3
        3 |     2014 |        2 |        0 |     2
(5 rows)

【讨论】:

  • 非常感谢,差不多了!我需要填充 total 列,并且需要零值而不是 NULL。
  • 零值呢?
  • 当您的解决方案应用于 4 个表连接时仍然存在问题。请参阅此处打开的新帖子:stackoverflow.com/q/44564673/2508539。再次感谢您的帮助!
  • @wiltomap 也回答了这个问题 - 使用括号或严格顺序或直接打开以获得想要的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 2018-12-23
  • 2022-01-26
  • 2015-02-25
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多