Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can this be done?

Status
Not open for further replies.

CaptainKebab

Programmer
Dec 7, 2009
1
US
Hi all, I'm writing the reports section for a bookstore app and I'm trying to figure out how to do a query only in sql (as opposed to loops in the code).

I want to show the top seller (book) for each book classification of book that the store sells.

This query involves two tables:
Book: ISBN, Title, Classification, etc
Order_Details: Order_No, ISBN, Copies, etc

What I need is a dataset returned like so:
Classification | ISBN | Title | Copies Sold
Fiction | 321.a | My Book | 327
Science | 156.b | Math 2 | 186

I've been fiddling around with it for a while but the closest I can get returns all books for each classification and the amount of copies sold for each book, or the amount of books sold in each classification without the top book.

It probably won't help but here are those two closest queries:

SELECT Book.Classification, Book.ISBN, COUNT(Order_Details.Copies) AS 'Total_Sales'
FROM Book, Order_Details
WHERE Book.ISBN = Order_Details.ISBN
GROUP BY Book.ISBN, Book.Classification
ORDER BY 'Total_Sales' DESC

and

SELECT DISTINCT(Book.Classification), COUNT(Order_Details.ISBN) * Order_Details.Copies AS 'Total_Sales'
FROM Book, Order_Details
WHERE Order_Details.ISBN = Book.ISBN
GROUP BY Book.Classification, Order_Details.Copies

Any help would be greatly appreciated, thanks!
 
A simple way to solve this is to create a view which does the calculations, and then use it to find me most sold books.

[tt]create view books_sold as
select b.*, sum(o.Copies) as Total_Sales
from book as b left join Order_Details as o on b.ISBN = o.ISBN
group by b.ISBN,b.Title, b.Classification;[/tt]


Then do something like[tt]
select * from books_sold as bs
where Total_Sales = (select max(Total_Sales) from books_sold
where Classification = bo.Classification);[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top