use*_*749 5 mysql alias group-by
有谁知道为什么我无法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;
Run Code Online (Sandbox Code Playgroud)
当作者没有图书销售时,我想在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;
Run Code Online (Sandbox Code Playgroud)
更新2
看起来您不需要在 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;
Run Code Online (Sandbox Code Playgroud)
示例输出:
+------------+------------+----------------+-------- --------+ | 作者 ID | 书号 | 总数量 | 总销售额 | +------------+------------+----------------+-------- --------+ | 1 | 1 | 12 | 12 278.50 | 278.50 | 1 | 3 | 没有书 | 没有销售 | | 1 | 小计 | 12 | 12 278.50 | 278.50 | 3 | 2 | 5 | 75.75 | 75.75 | 3 | 小计 | 5 | 75.75 | 75.75 | 所有作者 | 所有书籍 | 17 | 17 354.25 | 354.25 +------------+------------+----------------+-------- --------+
这是SQLFiddle演示
| 归档时间: |
|
| 查看次数: |
571 次 |
| 最近记录: |