Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL problem with aggregate functions in where clause

I am working on this SQL problem:

Show any purchase orders whose charged amount and actual amount are different. Show this by displaying the purchase order number, the POAmount for each purchase order, the actual amount (calculated by adding the prices of all items in the order), and the difference between the two. Sort the results to show those with the largest differences first.

I am getting the following code when running the sql statement below:

Error code -1, SQL state 42903: Invalid use of an aggregate function.

select 
  purchaseorder.ponum, 
  purchaseorder.amount, 
  sum(poitems.quantity*poitems.unitprice), 
  purchaseorder.amount-sum(poitems.quantity*poitems.unitprice)
from  purchaseorder, poitems
where 
  purchaseorder.ponum = poitems.ponum 
    and purchaseorder.amount!=sum(poitems.quantity*poitems.unitprice)
group by 
  purchaseorder.ponum, 
  purchaseorder.amount

I think it's because I'm using an aggregate function in my where clause.

How can I remedy this problem???

Thanks,

like image 786
novicePrgrmr Avatar asked Nov 03 '10 23:11

novicePrgrmr


People also ask

Why aggregate functions Cannot be used in WHERE clause?

Aggregate functions are not allowed because the WHERE clause is used for filtering data before aggregation. So while WHERE isn't for aggregation, it has other uses. To filter data based on an aggregate function result, you must use the HAVING clause.

Can SQL aggregate functions be used in WHERE clause?

An aggregate function can be used in a WHERE clause only if that clause is part of a subquery of a HAVING clause and the column name specified in the expression is a correlated reference to a group. If the expression includes more than one column name, each column name must be a correlated reference to the same group.

Can we use aggregate function with WHERE or GROUP BY clause?

The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

Which statement can not be used with the WHERE clause?

We cannot use the HAVING clause without SELECT statement whereas the WHERE clause can be used with SELECT, UPDATE, DELETE, etc. WE can use aggregate functions like sum, min, max, avg, etc with the HAVING clause but they can never be used with WHERE clause.


1 Answers

Try this:

select 
  purchaseorder.ponum, 
  purchaseorder.amount, 
  sum(poitems.quantity*poitems.unitprice),   
  purchaseorder.amount-sum(poitems.quantity*poitems.unitprice) 
from  purchaseorder, poitems 
where 
  purchaseorder.ponum = poitems.ponum 
group by 
  purchaseorder.ponum, 
  purchaseorder.amount 
having  
  purchaseorder.amount!=sum(poitems.quantity*poitems.unitprice)
like image 90
Jeff Hornby Avatar answered Sep 23 '22 16:09

Jeff Hornby