从第一个表加入两个带有计数的表

时间:2012-12-07 01:41:07

标签: postgresql postgresql-9.1

我知道这个问题有一个明显的答案,但我就像一个努力记住如何编写查询的菜鸟。我在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的结果集,table1中的accountid计数和table2读取。连接在table1.accountid = table2.customer_id。

结果集应如下所示:

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

count列反映了table1中每个accountid的行数。 read列是table2中与相同accountid相关联的值。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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
    ;