Subject Similar SQL query fails
Author Rick Debay
Fails with 'Cannot use an aggregate function in a WHERE clause, use
HAVING instead'

select
d.PRODUCTID, (d.AWP / d.QTY) awp_ppu,
d.GPI, d.PRODUCTID/100 ndc9
from
MDDB_DRUG d
where
d.GPI = ? and
d.PRODUCTID/100 = ? and
(d.AWP / d.QTY) <= ALL(
select MIN( d.AWP / d.QTY )
from MDDB_DRUG d2
where d.PRODUCTID/100 = d2.PRODUCTID/100 and d.GPI = d2.GPI
)

If I remove the MIN it prepares without an error, but I don't know if it
will return the same results (the column AWP is empty right now).

This verion (different database, same version of Firebird) works, no
error.

select
v1.NDC, (v1.PRICE / v1.TOT_QTY) awp_ppu,
v1.GPI, v1.NDC/100 ndc9
from
V_MDDB_DRUGITEM_AWP v1
where
v1.GPI = ? and
v1.NDC/100 = ? and
(v1.PRICE / v1.TOT_QTY) <= ALL(
select MIN( v2.PRICE / v2.TOT_QTY )
from V_MDDB_DRUGITEM_AWP v2
where v2.NDC/100 = v1.NDC/100 and v2.GPI = v1.GPI
)

Note that it contains the MIN function, and that it references a view
instead of a table.