OPDATERET2
-
Det ser ud til, at du ikke behøver at inkludere TotalSales i GROUP BY. Når du ser på din forespørgsel, giver det bare ingen mening. Bare forkast det fra det indre udvalg.
-
For at inkludere bøger, der ikke er blevet solgt, skal du bruge en outer join
Når det er sagt, kan din forespørgsel se ud
SELECT COALESCE(author_id, 'All Authors') author_id
, COALESCE(book_id, IF(author_id IS NULL, 'All Books', 'Subtotal')) book_id
, COALESCE(total_quantity, 'No books') total_quantity
, COALESCE(total_sales, 'No Sales') total_sales
FROM
(
SELECT author_id
, b.book_id
, SUM(quantity) total_quantity
, SUM(quantity * order_price) total_sales
FROM book_authors b LEFT JOIN order_details d
ON b.book_id = d.book_id
WHERE author_sequence = 1
GROUP BY Author_id, Book_ID WITH ROLLUP -- you don't need TotalSales here
) q;
Eksempeloutput:
+-------------+-----------+----------------+-------------+ | author_id | book_id | total_quantity | total_sales | +-------------+-----------+----------------+-------------+ | 1 | 1 | 12 | 278.50 | | 1 | 3 | No books | No Sales | | 1 | Subtotal | 12 | 278.50 | | 3 | 2 | 5 | 75.75 | | 3 | Subtotal | 5 | 75.75 | | All Authors | All Books | 17 | 354.25 | +-------------+-----------+----------------+-------------+
Her er SQLFiddle demo