GROUP BY clause with alias?

Viewed 604

Does anyone know why I am not able to group TotalSales in this query and if so how can I fix this:

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;

I wanted to include 'no sales' under TotalSales when an author has no book sales. Here is the updated version. I'm not positive it is correct but I do have output which seems to solve the problem. Here it is:

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;
2 Answers
Related