gpt4 book ai didi

sql - 使用 PostgreSQL 合并表

转载 作者:行者123 更新时间:2023-11-29 12:03:08 24 4
gpt4 key购买 nike

这个问题的标题不准确,但我不知道如何总结。可以的话请再写一遍!

这是两个表的摘录:

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);

最佳答案

你可能是looking对于 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)

关于sql - 使用 PostgreSQL 合并表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44562726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com