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の数をtable1に表示し、table2から読み取ることです。結合はtable1.accountid=table2.customer_idにあります。

結果セットは次のように表示されます。

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

count列は、各accountidのtable1の行数を反映しています。読み取り列は、同じaccountidに関連付けられたtable2の値です。

4

3 に答える 3

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 に答える
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 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 に答える