2017-06-15 33 views
2

這個問題的標題不準確,但我不知道如何總結它。如果可以,請隨時再寫一遍!用PostgreSQL合併表格

下面是兩個表的摘錄:

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

爲什麼2012有一行和2012,2013,2017 - 三?.. –

+0

不確定要理解您的問題...代碼是地理區域代碼,而不是ID。 – wiltomap

+0

我猜是什麼?..你想要一個完整的外連接?.. –

回答

3

宇大概是lookingFULL 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) 
+0

非常感謝,差不多是這樣!我需要'total'列被填充,並且也是零值而不是NULL。 – wiltomap

+0

是的 - 已經注意到並修復了,謝謝 –

+0

零值是什麼? – wiltomap