我尝试在postgresql中使用sum函数进行查询,以获得3种不同行类型(root、dynamic、test)的总和。我第一次尝试使用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
我能得到帮助吗?谢谢:)
2条答案
按热度按时间ix0qys7i1#
考虑使用
filter
aggreagate函数的语法,这是标准sql,postgres支持:如果你写这篇文章时没有
filter
语法(与第一次尝试一样),可移植语法是:fafcakar2#
你可以用
filter
对于条件聚合:您不需要外部聚合,但可以更简单地以行而不是列的形式返回结果:
注意:我强烈反对使用转义列名。定义表时不要使用双引号,也不要在查询中使用双引号。