【发布时间】:2022-01-07 02:05:08
【问题描述】:
SQL 新手,谷歌搜索无济于事。这是架构:
"users"
Column | Type |
---------------------+--------------------------+
id | text |
name | text |
title | text |
org_id | text |
type. | text |
"organizations"
Column | Type |
--------------------------------+--------------------------+
id | text |
name | text |
"posts"
Column | Type |
-------------------+--------------------------+
id | text |
title | text |
content | jsonb[] |
owner_id | text |
org_id | text |
is_public | boolean |
我的目标是在一张表中显示每个组织有多少私人主题、管理员和标准用户,如下所示:
Org | Users | Admins | Private Posts
----------+-------+-------+---------------
Org1 | 56 | 10 | 22
Org2 | 111 | 10 | 34
现在,我只得到这个:
Org | Count | Type | Private Posts
----------+-------+-------+---------------
Org1 | 10 | admin | 22
Org2 | 111 | user | 34
Org1 | 56 | user | 22
Org2 | 10 | admin | 34
使用:
SELECT t1.id as "Org", t1.cnt as "Count", t1.type as "Type", t2.cnt as "Private Posts" from
(SELECT COUNT(u.type) as "cnt", u.type as "type", o.id FROM "users" AS u JOIN
"organizations" AS o ON o.id=u.org_id GROUP BY u.type, o.id) as t1 join
(SELECT COUNT(org_id) as "cnt", org_id from posts WHERE is_public = False group
by org_id) as t2 on t2.org_id = t1.id;
我基本上尝试加入用户和组织并根据组织和用户类型(t1)计数,然后在帖子(t2)中统计公共帖子,并尝试根据组织id加入t1和t2。任何帮助表示赞赏。
【问题讨论】:
标签: sql postgresql join count aggregate-functions