by codegeek · 12y ago · 0 comments
- price could be 0.0 for a book
- Total sales means the sum and not count
- Date format will be yyyymmdd (if not, assume that we converted in Oracle or Sybase)
SELECT a.name, SUM(s.price) FROM authors a
INNER JOIN books b ON (a.id=b.author_id)
LEFT OUTER JOIN sales s ON (b.id = s.book_id)
GROUP BY a.name
HAVING (s.date >= '20131101' AND s.date <= '20131130')Something like this could work (without going for an alternate approach such as Unions or sub-selects):
SELECT a.name, ISNULL(SUM(s.price), 0.0) FROM authors a
INNER JOIN books b ON (a.id=b.author_id)
LEFT OUTER JOIN sales s ON (b.id = s.book_id)
GROUP BY a.name, s.date
HAVING (ISNULL(s.date, '20131101') >= '20131101' AND ISNULL(s.date, '20131101') <= '20131130')
Edit: Actually might be better to keep the null in the results like the original query. It's definitely better to know whether a book sold 1000 copies for $0.00 each or if no copies were sold.If it were me, I'd prefer to see those that made no sales based on the question. I guess if I didn't want to see them, I would ask for "where sales are greater than $0.00".