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 的结果集、table1 中 accountid 的计数并从 table2 读取。联接在 table1.accountid = table2.customer_id 上。

结果集应如下所示:

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

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

4

3 回答 3

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
    ;
于 2012-12-07T10:31:14.177 回答
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
于 2012-12-07T10:26:03.687 回答
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
于 2012-12-07T02:45:46.167 回答