SqlExceptionHelper:错误:函数计数(字符变化,整数)不存在

时间:2018-03-09 11:59:21

标签: sql postgresql

我有一个spring应用程序,我有一个使用以下语法的本机查询:

select  
    COUNT(DISTINCT person.id,(CASE WHEN salary_person.rating = 'Satisfactory' THEN 1 END)) AS totalSatisfactory, 
    COUNT(DISTINCT person.id,(CASE WHEN salary_person.rating = 'Unsatisfactory' THEN 1 END)) AS totalUnsatisfactory
    from person
    join salary_person on person.id = salary_person.person_id;   

我收到错误:

 ERROR: function count(character varying, integer) does not exist

作为数据库,我使用PostgreSQL。我在mysql中提到,查询正在运行。

1 个答案:

答案 0 :(得分:3)

Postgres不支持count()多列。但是,您可以通过使用类似以下内容的方式将两列都转换为匿名记录类型的单个列:(col_one, col_two) - 这是匿名记录类型的单个列。

select COUNT(DISTINCT (person.id,(CASE WHEN salary_person.rating = 'Satisfactory' THEN 1 END))) AS totalSatisfactory, 
       COUNT(DISTINCT (person.id,(CASE WHEN salary_person.rating = 'Unsatisfactory' THEN 1 END))) AS totalUnsatisfactory
from person
  join salary_person on person.id = salary_person.person_id;   

注意两列的括号。

然而,在Postgres中,通过使用带有filter子句的条件聚合,您可以更优雅地执行所需操作:

select COUNT(DISTINCT person.id) filter (where salary_person.rating = 'Satisfactory') AS totalSatisfactory, 
       COUNT(DISTINCT person.id) filter (where salary_person.rating = 'Unsatisfactory') AS totalUnsatisfactory
from person
  join salary_person on person.id = salary_person.person_id;