Reputation: 77
How do I find the most popular book among all customers from the table above? (cid = 'customer id')?
I have
select Title, sum(c.quantity) from cart c group by c.ISBN;
which gives me the following results
+-----------------------------------------+-----------------+ | Title | sum(c.quantity) | +-----------------------------------------+-----------------+ | Writing Skills | 5 | | Fundamentals of Database Systems | 2 | | Database Management Systems | 5 | | Data Mining, Practical Machine Learning | 4 | +-----------------------------------------+-----------------+
I know the Max() function in mysql can achieve my goal, but I do not know to implement Max() and Sum() together.
Thanks!
Upvotes: 1
Views: 106
Reputation: 2794
The following SQL statement should give you the book with the most quantity
SELECT
Title,
sum(c.quantity) AS total_count
FROM
cart c
GROUP BY
c.ISBN
ORDER BY
total_count DESC
LIMIT 1
Note: You really should put the books in a seperate table titled "books" with two columns, "id" and "title". You can then change the "title" column in your original table to "book_id" and make it a foreign key to books.id. This will greatly improve the speed of your SQL calls.
Hope this helps!
Upvotes: 2
Reputation: 64476
To get most popular book/books you can use following query
select c.ISBN,c.Title, sum(c.quantity) soldQuantity
from cart c
group by c.ISBN,c.Title
having soldQuantity = (
select sum(quantity)
from cart
group by ISBN,Title
order by sum(quantity) desc
limit 1
)
Note there can be more than 1 books which share same highest quantity
Upvotes: 2
Reputation: 1714
Hi one approach would be using sub queries like this:
SELECT TITLE, MAX (SUMMATION)
FROM (SELECT TITLE, SUM (C.QUANTITY) SUMMATION
FROM CART C
GROUP BY TITLE, C.ISBN) LIST
GROUP BY TITLE, SUMMATION
Upvotes: -1