有谁知道为什么我无法在此查询中对TotalSales
进行分组,如果是,我该如何解决此问题:
select coalesce(Author_ID, 'All Authors') as Author_ID
, case when Author_ID is null then ' ' else coalesce(Book_ID, 'All Books') end as Book_ID
, TotalQuantity
, coalesce(TotalSales, 'No Sales') as TotalSales
from (
select author_id as Author_ID
, book_id as Book_ID
, sum(quantity) as TotalQuantity
, sum(quantity * order_price) as TotalSales
from a_bkinfo.book_authors
join a_bkorders.order_details using (book_id)
where author_sequence = 1
group by Author_id, Book_ID, TotalSales with rollup
) tbl;
当作者没有图书销售时,我想在TotalSales下包含“无销售”。这是更新版本。我不肯定它是正确的,但我确实有输出,似乎解决了这个问题。这是:
select coalesce(Author_ID, 'All Authors') as Author_ID
, case when Author_ID is null then ' ' else coalesce(Book_ID, 'All Books') end as Book_ID
, NumOrders
, coalesce(TotalSales, 'No Sales') as TotalSales
from ( select author_id as Author_ID
, book_id as Book_ID
, count(Distinct order_id) AS NumOrders
,(Select sum(quantity * order_price) from a_bkorders.order_details) as TotalSales
from a_bkorders.order_headers
join a_bkorders.order_details using (order_id)
join a_bkinfo.book_authors using (book_id)
where author_sequence = 1
group by Author_ID, Book_ID, TotalSales with rollup) tbl;
答案 0 :(得分:1)
<强> UPDATED2 强>
看起来您不需要在GROUP BY中包含TotalSales。看看你的查询它没有任何意义。只是从内部选择中抛弃它。
要包含尚未售出的图书,您必须使用外部联接
据说你的查询可能看起来像
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;
示例输出:
+-------------+-----------+----------------+-------------+ | 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 | +-------------+-----------+----------------+-------------+
这是 SQLFiddle 演示
答案 1 :(得分:0)
这是如何工作的(订单):
FROM
条款WHERE
条款GROUP BY
条款HAVING
条款SELECT
条款ORDER BY
条款在这种情况下,你的别名是在5步创建的,购买的地方是2步。您需要使用计算的TotalSales
创建子查询,然后在外部查询中使用GROUP
。