DIPERBARUI2
-
Sepertinya Anda tidak perlu menyertakan TotalSales di GROUP BY. Melihat permintaan Anda, itu tidak masuk akal. Buang saja dari pilihan dalam.
-
Untuk memasukkan buku yang belum terjual harus menggunakan outer join
Meskipun demikian, kueri Anda mungkin terlihat seperti
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;
Contoh keluaran:
+-------------+-----------+----------------+-------------+ | 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 | +-------------+-----------+----------------+-------------+
Ini SQLFiddle demo