【问题标题】:PostgreSQL count of records by statusPostgreSQL 按状态统计的记录数
【发布时间】:2018-02-06 18:03:36
【问题描述】:

在我的 PostgreSQL 数据库中,我有 users 表,其中包含以下列:

id - integer
email - string
blocked - boolean

现在我想要 sql 查询返回以下结果:

total:                blocked:                unblocked
total count of users  count of blocked users  count of users that are not blocked

如何在 PostgreSQL 中做到这一点?

【问题讨论】:

    标签: sql postgresql aggregate-functions


    【解决方案1】:

    你可以试试这个:

    SELECT COUNT(ID) AS USER_RC
         , SUM(CASE WHEN BLOCKED=TRUE THEN 1 ELSE 0 END) AS BLOCKED_RC
         , SUM(CASE WHEN BLOCKED=TRUE THEN 0 ELSE 1 END) AS UNBLOCKED_RC  
    FROM TX1;
    

    或者如果您愿意(它只使用两个聚合函数):

    SELECT A.*, USER_RC-BLOCKED_RC AS UNBLOCKED_RC
    FROM (SELECT COUNT(ID) AS USER_RC, SUM(CASE WHEN BLOCKED=TRUE THEN 1 ELSE 0 END) AS BLOCKED_RC 
         FROM TX1) A
    ;
    

    样本数据:

    INSERT INTO TX1 VALUES (1,'aaa',FALSE);
    INSERT INTO TX1 VALUES (2,'bbb',TRUE);
    INSERT INTO TX1 VALUES (3,'ccc',TRUE);
    INSERT INTO TX1 VALUES (4,'ddd',TRUE);
    INSERT INTO TX1 VALUES (5,'eee',FALSE);
    

    输出:

    user_rc blocked_rc  unblocked_rc
        5       3           2
    

    【讨论】:

      【解决方案2】:

      count()filter: 一起使用

      select
          count(*) as total,
          count(*) filter (where blocked) as blocked,
          count(*) filter (where not blocked) as unblocked
      from users
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-06
        • 1970-01-01
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多