【问题标题】:Join two tables with count from first table从第一个表中加入两个表
【发布时间】:2012-11-25 04:39:05
【问题描述】:

我知道这个问题有一个明显的答案,但我就像一个菜鸟,试图记住如何编写查询。我在 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 关联的值。

【问题讨论】:

  • 我希望您的实际架构具有合理的名称,而不是 table1table2,并且您并没有真正加入 accountid = customer_id
  • 我尝试过但未能理解这一点:The objective of the query is to display a result set of accountid's, count of accountid's in table1 and read from table2. The join is on table1.accountid = table2.customer_id. 请提供示例值以及您的结果应该是什么样子。另外,总是,您的 PostgreSQL 版本。
  • 是的,我删除了真实姓名以保护无辜者。此外,恰好 accountid 和 customer_id 相同(旧主机)。
  • accountid 计数读取

标签: postgresql postgresql-9.1


【解决方案1】:
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】:
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

【讨论】:

  • 谢谢,但我遇到的麻烦是在结果集中包含两个表中的列以及计数(*)。此答案中的三列来自同一个表,即 table2。
【解决方案3】:
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
    ;

【讨论】:

  • 糟糕,经过检查,我发现这个微不足道的答案与@Sn00k4h 的几乎相同
猜你喜欢
  • 1970-01-01
  • 2021-09-09
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2015-11-12
  • 2020-05-23
相关资源
最近更新 更多