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,
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With