Question

I'm trying to get the average retail price of books by publisher name and category. I only want to include the categories 'CHILDREN' and 'COMPUTER' and the groups with an average retail price greater than $50. I'm stuck!

SELECT PUBLISHER.NAME, BOOKS.CATEGORY
  TO_CHAR(AVG(BOOKS.RETAIL), '99.99') "Avg Retail"
FROM BOOKS, PUBLISHER
WHERE BOOKS.category='CHILDREN' or BOOKS.category='COMPUTER' and AVG > 50;
Était-ce utile?

La solution

You need to learn several things about writing SQL queries.

First, always use explicit join syntax. An easy rule is: Never use commas in the from clause.

Second, you need to join the two tables on something. I am guessing a field like PublisherId, but you might actually know the right field.

Third, in is much clearer than a sequence of or clauses.

Four, you cannot include avg() in a where clause. That is the purpose of the having clause.

Five, if you are doing an aggregation expecting multiple result rows, you need a group by.

SELECT p.NAME, b.CATEGORY, TO_CHAR(AVG(b.RETAIL), '99.99') as "Avg Retail"
FROM BOOKS b JOIN
     PUBLISHER p
     on b.PublishedId = b.PublisherId
WHERE b.category in ('CHILDREN', 'COMPUTER')
GROUP BY p.NAME, b.CATEGORY
HAVING AVG(b.RETAIL) > 50;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top