【问题标题】:SQL query using Sum() and count() functions使用 Sum() 和 count() 函数的 SQL 查询
【发布时间】:2020-08-05 12:49:01
【问题描述】:

我正在尝试使用 SUM 函数在 PostgresQL 中进行查询,以获得总共 3 种不同的行类型(根、动态、测试)。我第一次尝试使用 Sum() 函数,第二次尝试使用 Count() 函数;可悲的是,两者都没有工作。我预计会出现语法错误(因为我是使用 SQL 的初学者),但我不确定它是什么以及如何修复它!

第一次尝试 Sum() 函数:

SELECT 
sum(case when "exerciseType" = 'ROOT') as total_root_exercises, 
sum(case when "exerciseType" = 'DYNAMIC') as total_dynamic_exercises,
sum(case when "exerciseType" = 'TEST') as total_test_exercises
FROM exer 
GROUP BY "exerciseType"

第二次尝试使用 Count() 函数:

select 
count(*) as total_root_exercises
where "exerciseType" = 'ROOT',
count(*) as total_Dynamic_exercises
where "exerciseType" in('DYNAMIC'),
count(*) as total_test_exercises
where "exerciseType" in('TEST')
FROM exer

我可以在这方面寻求帮助吗?谢谢你:)

【问题讨论】:

  • 通常情况下与docs一起使用。提供的答案是它的替代方案。

标签: sql postgresql count sum pivot


【解决方案1】:

考虑使用filter 语法来聚合函数,这是标准 SQL 并且 Postgres 支持:

select 
    count(*) filter(where "exerciseType" = 'ROOT'   ) as total_root_exercises,
    count(*) filter(where "exerciseType" = 'DYNAMIC') as total_Dynamic_exercises,
    count(*) filter(where "exerciseType" = 'TEST'   ) as total_test_exercises 
FROM exer

如果您要在没有filter 语法的情况下编写此代码(如您的第一次尝试),则可移植语法是:

select 
    sum(case when "exerciseType" = 'ROOT'    then 1 else 0 end) as total_root_exercises,
    sum(case when "exerciseType" = 'DYNAMIC' then 1 else 0 end) as total_Dynamic_exercises,
    sum(case when "exerciseType" = 'TEST'    then 1 else 0 end) as total_test_exercises 
FROM exer

【讨论】:

    【解决方案2】:

    您可以使用filter 进行条件聚合:

    SELECT count(*) filter (where "exerciseType" = 'ROOT') as total_root_exercises, 
           count(*) filter (where "exerciseType" = 'DYNAMIC') as total_dynamic_exercises,
           count(*) filter (where "exerciseType" = 'TEST') as total_test_exercises
    FROM exer ;
    

    您不需要外部聚合,尽管您可以更简单地以行而不是列的形式返回结果:

    select "exerciseType", count(*)
    from exer
    group by "exerciseType";
    

    注意:我强烈反对使用转义的列名。定义表时不要使用双引号,也不要在查询中使用它们。

    【讨论】:

    • 对列名使用双引号是唯一有效的方法,至少在 Postgres 中是这样。当调用一个全是小写字母的列名时,它可以不带引号,但是当列名至少有一个大写字母时,比如在“exerciseType”的情况下,我必须使用引号。或者我还能怎么做?
    • @user6688 。 . .那是因为表格是用双引号定义的。不要那样做!如果其他人犯了这个错误,你会坚持下去。你确实意识到这是第一个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2020-02-12
    • 2017-02-16
    • 1970-01-01
    相关资源
    最近更新 更多