postgresql 如何修复错误“WHERE 中不允许使用聚合函数”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41277189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:28:31  来源:igfitidea点击:

How to fix error “aggregate functions are not allowed in WHERE”

postgresql

提问by faza

How to fi this error

如何解决这个错误

Err] ERROR: aggregate functions are not allowed in WHERE

Err] 错误:WHERE 中不允许使用聚合函数

this my query

这是我的查询

select count(case daftar.daftar when 'sd' then 1 else null end) as sd,
 count(case daftar.daftar when 'smp' then 1 else null end) as smp,
 count(case daftar.daftar when 'sma' then 1 else null end) as sma
from daftar
join gelombang on  daftar.gel=gelombang.id
join ajaran on ajaran.id=gelombang.id_ajar
join tahun on tahun.id=ajaran.tahun
where daftar.status='terima' and daftar.pindahan='no' and tahun.id= max(tahun.id)

采纳答案by Tim Biegeleisen

One option is to use a subquery to calculate that max value:

一种选择是使用子查询来计算最大值:

select count(case daftar.daftar when 'sd' then 1 else null end) as sd,
       count(case daftar.daftar when 'smp' then 1 else null end) as smp,
       count(case daftar.daftar when 'sma' then 1 else null end) as sma
from daftar
inner join gelombang
    on daftar.gel = gelombang.id
inner join ajaran
    on ajaran.id = gelombang.id_ajar
inner join tahun
    on tahun.id = ajaran.tahun
where daftar.status = 'terima' and
      daftar.pindahan = 'no'   and
      tahun.id = (select max(id) from tahun)

回答by allen

You can use "HAVING" to tackle this:

您可以使用“HAVING”来解决这个问题:

HAVING tahun.id= max(tahun.id)

有 tahun.id= max(tahun.id)

select count(case daftar.daftar when 'sd' then 1 else null end) as sd,
 count(case daftar.daftar when 'smp' then 1 else null end) as smp,
 count(case daftar.daftar when 'sma' then 1 else null end) as sma
from daftar
join gelombang on  daftar.gel=gelombang.id
join ajaran on ajaran.id=gelombang.id_ajar
join tahun on tahun.id=ajaran.tahun
where daftar.status='terima' and daftar.pindahan='no' 
HAVING tahun.id= max(tahun.id)

回答by Mr. Skip

Aggregates functions we use only in SELECT block. You can use inner select for this case:where daftar.status='terima' and daftar.pindahan='no' and tahun.id=(select max(id) from tahun)

我们仅在 SELECT 块中使用的聚合函数。您可以在这种情况下使用内部选择:where daftar.status='terima' and daftar.pindahan='no' and tahun.id=(select max(id) from tahun)

回答by kimdasuncion12

use a subquery, group by or having clause

使用子查询、分组依据或具有子句