faza
faza

Reputation: 151

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

How to fi this error

Err] ERROR: aggregate functions are not allowed in 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)

Upvotes: 8

Views: 22831

Answers (4)

allen
allen

Reputation: 366

You can use "HAVING" to tackle this:

HAVING 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)

Upvotes: 8

kimdasuncion12
kimdasuncion12

Reputation: 349

use a subquery, group by or having clause

Upvotes: 1

Mr. Skip
Mr. Skip

Reputation: 417

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)

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521073

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)

Upvotes: 3

Related Questions