【问题标题】:SQL Query JOIN and AggregateSQL 查询 JOIN 和聚合
【发布时间】: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


    【解决方案1】:

    考虑一个名为条件聚合的概念,它根据条件逻辑将结果转置到所需的宽格式列。 Postgres 为此类查询维护有用的 FILTER,但也可以使用与其他 RDBMS 共享的 CASE 语句:

    SELECT o.id AS "Org",
           COUNT(*) FILTER(WHERE u.type = 'user') AS "Users",
           COUNT(*) FILTER(WHERE u.type = 'admin') AS "Admins",
           COUNT(*) FILTER(WHERE is_public = False) AS "Private Posts"
    FROM users u
    JOIN organizations o 
       ON o.id = u.org_id
    JOIN posts p 
       ON o.id = p.org_id
    GROUP BY o.id;
    

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2023-02-03
      • 2012-08-26
      • 1970-01-01
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多