7

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)
faza
  • 141
  • 1
  • 2
  • 12
  • 1
    This problem already discussed here: http://stackoverflow.com/questions/21466123/error-aggregates-not-allowed-in-where-clause-in-postgresql – Maksym Voronytskyi Dec 22 '16 at 06:47
  • BTW: You can simplify the `CASE`expressions, e.g. `COUNT(daftar.daftar = 'sd' OR NULL)`. – clemens Dec 22 '16 at 06:49
  • Possible duplicate of [ERROR: Aggregates not allowed in WHERE clause in postgreSQL](http://stackoverflow.com/questions/21466123/error-aggregates-not-allowed-in-where-clause-in-postgresql) – Aziz Shaikh Jan 20 '17 at 10:00

4 Answers4

7

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)
allen
  • 356
  • 5
  • 8
3

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)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
3

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)

Mr. Skip
  • 417
  • 4
  • 10
1

use a subquery, group by or having clause

kimdasuncion12
  • 319
  • 2
  • 4
  • 17