【问题标题】:I need to get count of total count for the query I had in postgresql我需要获取我在 postgresql 中的查询的总数
【发布时间】:2021-11-17 02:49:54
【问题描述】:

我创建了一个如下的选择查询,现在我需要在单独的行中获取“生成的创意数”列的总数作为总数,这将计算特定idea_sector 和idea_industry 组合的单个计数.

查询:

 select c.idea_sector,c.idea_industry,
count(*) as "No.of Ideas generated"
from hackathon2k21.consolidated_report c
group by idea_sector,idea_industry
order by idea_sector ,idea_industry

输出:

 ----------------------------------------------------------------------
   idea_sector         idea_industry                 No.of Ideas generated
    -----------------------------------------------------------------------
    COMMUNICATION-ROC   TELECOMMUNICATIONS            1 
    Cross Sector        Cross Industry                5 
    DISTRIBUTION        TRAVEL AND TRANSPORTATION     1 
    FINANCIAL SERVICES  BANKING                       1
    PUBLIC              HEALTHCARE                    1

所需输出:

    ----------------------------------------------------------------------
       idea_sector         idea_industry                 No.of Ideas generated
        -----------------------------------------------------------------------
        COMMUNICATION-ROC   TELECOMMUNICATIONS            1 
        Cross Sector        Cross Industry                5 
        DISTRIBUTION        TRAVEL AND TRANSPORTATION     1 
        FINANCIAL SERVICES  BANKING                       1
        PUBLIC              HEALTHCARE                    1
------------------------------------------------------------------------
        Total                                             9

【问题讨论】:

  • 你想要grouping sets

标签: sql database postgresql psql


【解决方案1】:

您可以通过分组集来完成此操作。这就是我们在 GROUP BY 子句中告诉 postgres 我们希望看到为聚合列分组的结果集的所有不同方式

SELECT 
    c.idea_sector,
    c.idea_industry,
    count(*) as "No.of Ideas generated"
FROM hackathon2k21.consolidated_report c
GROUP BY
    GROUPING SETS (
       (idea_sector,idea_industry),
       ())
ORDER BY idea_sector ,idea_industry;

这会生成两个分组集。一个按 idea_sector, idea_industry 粒度分组,就像在您现有的 sql 中一样,另一个按任何内容分组,本质上是创建一个完整的表 Total

【讨论】:

  • 非常感谢,它帮助了我,唯一的问题是我们没有从中得到“总”标签
【解决方案2】:

最简单的方法似乎是像这样添加一个 UNION ALL 运算符:

select c.idea_sector,c.idea_industry,
count(*) as "No.of Ideas generated"
from hackathon2k21.consolidated_report c
group by idea_sector,idea_industry
--order by idea_sector ,idea_industry

UNION ALL
SELECT 'Total', NULL, COUNT(*)
from hackathon2k21.consolidated_report

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 2011-02-03
    • 2020-04-19
    • 1970-01-01
    • 2016-05-29
    • 2015-04-09
    • 2019-06-13
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多