我在Postgres 9.6工作。我有一张资产表:
CREATE TABLE assets (
name varchar,
company_number varchar
);
公司表(两个字段中的company_number
是相关的,虽然没有正式的外键) - 公司可以有很多资产:
CREATE TABLE companies (
company_number varchar primary key,
name varchar
);
公司董事的表格,公司的外键 - 公司可以有很多董事:
CREATE TABLE directors (
id serial primary key,
company_number varchar REFERENCES companies(company_number),
person_name varchar
);
我可以简单地获得大多数公司参与哪些董事的排名列表,如下所示:
SELECT person_name, count(*) AS num_companies
FROM directors
GROUP BY person_name
ORDER BY num_companies DESC;
我可以按如下方式获得每位董事拥有的资产数量的排名列表(我认为这是正确的):
SELECT q.person_name, count(*) as num_assets FROM
(SELECT a.name, c.company_number, c.person_name AS person_name
FROM directors d
LEFT JOIN assets a
ON a.company_number=d.company_number) q
GROUP BY q.person_name ORDER by num_assets DESC;
但是如何在一个命令中得到两个?换句话说,我想要一份完整的董事名单,包括他们参与的公司数量,以及这些公司控制的资产数量。
更新:根据要求,这是用于创建表和数据的示例SQL:
CREATE TABLE assets (
name varchar,
company_number varchar
);
INSERT INTO assets VALUES ('foo', 1), ('bar', 1), ('baz', 2), ('bar', 2), ('fii', 3);
CREATE TABLE companies (
company_number varchar primary key,
name varchar
);
INSERT INTO companies VALUES (1, 'acme corp'), (2, 'intergalactic holdings inc'), (3, 'intergalactic shellco inc');
CREATE TABLE directors (
id serial primary key,
company_number varchar REFERENCES companies(company_number),
person_name varchar
);
INSERT INTO directors(company_number, person_name) VALUES (1, 'arthur dent'), (1, 'trillian'), (2, 'ford prefect'), (3, 'ford prefect');
这些是我想得到的结果:
person_name,num_companies,num_assets
ford prefect,2,3
arthur dent,1,2
trillian,1,2
答案 0 :(得分:1)
我想要一份完整的董事名单,包括他们参与的公司数量,以及这些公司控制的资产数量
如果我正确理解,你需要这样的东西:
select directors.person_name, count(distinct directors.company_number) as company_count, count(distinct name) as asset_count
from directors
join assets
on directors.company_number = assets.company_number
group by directors.person_name;