2012-12-07 117 views
2

我知道這個問題有一個明顯的答案,但我像一個小白試圖記住如何編寫查詢。我在PostgreSQL如下表結構:從第一個表中加入兩個表格

CREATE TABLE public.table1 (
    accountid BIGINT NOT NULL, 
    rpt_start DATE NOT NULL, 
    rpt_end DATE NOT NULL, 
    CONSTRAINT table1_pkey PRIMARY KEY(accountid, rpt_start, rpt_end) 
) 
WITH (oids = false); 

CREATE TABLE public.table2 (
    customer_id BIGINT NOT NULL, 
    read VARCHAR(255), 
    CONSTRAINT table2 PRIMARY KEY(customer_id) 
) 
WITH (oids = false); 

查詢的目的是顯示一個結果集ACCOUNTID的,ACCOUNTID在表1的計數,並從表2讀取。連接在table1.accountid = table2.customer_id上。

結果集應如下所示:

accountid  count  read 
1234   2   100 
1235   9   110 
1236   1   91 

計數柱反映在表1每個ACCOUNTID的行數。讀取列是來自table2的與同一個accountid關聯的值。

+0

我希望你的實際模式有合理的名稱,而不是'table1'和'table2',那你真的不加入就'ACCOUNTID = customer_id'。 – willglynn

+0

我試過並沒有弄清楚這個問題:「查詢的目的是顯示accountid的結果集,在table1中顯示accountid的計數並從table2中讀取。該連接在table1.accountid = table2.customer_id.'請提供示例值和結果應該是什麼樣子。另外,作爲* always *,你的PostgreSQL版本。 –

+0

是的,我刪除了實際名稱以保護無辜者。另外,accountid和customer_id是相同的(傳統大型機)。 – user1884159

回答

0
select accountid, "count", read 
from 
    (
     select accountid, count(*) "count" 
     from table1 
     group by accountid 
    ) t1 
    inner join 
    table2 t2 on t1.accountid = t2.customer_id 
order by accountid 
+0

這很好。謝謝!我知道我錯過了一個關鍵概念。這釘爲我。 – user1884159

0
SELECT table2.customer_id, COUNT(*), table2.read 
FROM table2 
    LEFT JOIN table1 ON (table2.customer_id = table1.accountid) 
GROUP BY table2.customer_id, table2.read 
+0

謝謝,但我遇到的麻煩是在結果集中包括來自兩個表的列以及count(*)。這個答案中的三列來自同一張表,即table2。 – user1884159

0
SELECT t2.customer_id, t2.read, COUNT(*) AS the_count 
FROM table2 t2 
JOIN table1 t1 ON t1.accountid = t2.customer_id 
GROUP BY t2.customer_id, t2.read 
    ; 
+0

哎呀,經過檢查,我發現這個微不足道的答案几乎和@ Sn00k4h的一樣 – wildplasser

相關問題