Tas
Tas

Reputation: 17

SQL "not a single-group group function" Error on query

SELECT B.TITLE, TO_CHAR(SUM((B.COST*OI.QUANTITY)-OI.PAIDEACH), '$999.99')
AS "Profit"
FROM ORDERS O JOIN ORDERITEMS OI
on o.order# = oi.order#
JOIN BOOKS B ON OI.ISBN = B.ISBN
WHERE O.ORDER# = 1002;

THE GOAL

Determine the amount of total profit generated by the book purchased on order 1002. Display the book title and profit. The profit should be formatted to display a dollar sign and two decimal places. Take into account that the customer might not pay the full retail price, and each item ordered can involve multiple copies.

THE PROBLEM

So when trying to run the stated code above I get the error "not a single-group group function". I've tried grouping the whole statement on order# and the title, although when I do this I get the error "FROM keyword not found where expected".

Upvotes: 1

Views: 1026

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1271171

You need a group by clause:

SELECT B.TITLE, TO_CHAR(SUM((B.COST*OI.QUANTITY)-OI.PAIDEACH), '$999.99')
AS "Profit"
FROM ORDERS O JOIN ORDERITEMS OI
on o.order# = oi.order#
JOIN BOOKS B ON OI.ISBN = B.ISBN
WHERE O.ORDER# = 1002
group by b.title

Your problem arises because the select clause has a sum() in it. This suggests an aggregation query. Without a group by, SQL assumes that one row will be returned. However, you have a field b.title that is not aggregated -- hence the error.

Upvotes: 0

Taryn
Taryn

Reputation: 247880

Well part of your problem is you are missing the GROUP BY clause:

SELECT B.TITLE, 
  TO_CHAR(SUM((B.COST*OI.QUANTITY)-OI.PAIDEACH), '$999.99') AS "Profit"
FROM ORDERS O 
JOIN ORDERITEMS OI
  on o.order# = oi.order#
JOIN BOOKS B 
  ON OI.ISBN = B.ISBN
WHERE O.ORDER# = 1002
GROUP BY B.TITLE;

Whenever you are using an aggregate function, you need to include a GROUP BY for the columns that are in the select list but not in an aggregate function. So you have to add a GROUP BY B.TITLE to your query.

Upvotes: 1

Dan Bracuk
Dan Bracuk

Reputation: 20804

You have a sum() in your select clause and you don't have a group by clause. That caused your query to crash.

Upvotes: 0

Related Questions