【问题标题】:I need assistance with a query using group by with rollup我需要使用 group by 和汇总的查询帮助
【发布时间】:2013-12-13 06:02:13
【问题描述】:

我正在尝试在第一列中显示订单年份,在第二列中显示月份。另外,按月和按年显示总计以及总计。此外,显示消息“年度总计”和“总计”而不是空值。结果按年和月排序。

我不断收到错误消息(“字段列表”中的“未知列”“订单日期”)有人可以帮助我吗?

 select coalesce(year(order_date), 'Grand Total') as Year
, case when year(order_date) is null then ' ' else coalesce(month(order_date), 'Year Total') end as 
Month 
, AmntDue 
, NumberOfBooksPurch  
from (    
     select   year(order_date) as Year 
            , month(order_date) as Month
            ,  sum(quantity * order_price) as AmntDue    
            ,  count(order_id) as NumberOfBooksPurch    
            from a_bkorders.order_headers   
            join a_bkorders.order_details using (order_id)       
            group by year(order_date), month(order_date), order_id with rollup
     ) tbl;

【问题讨论】:

    标签: mysql aggregate-functions rollup


    【解决方案1】:

    order_date 是原始表中的值,但子查询不会返回它,因此您无法在外部查询中引用它。使用子查询返回的别名:

    select coalesce(Year, 'Grand Total') as Year
    , case when Year is null then ' ' else coalesce(Month, 'Year Total') end as 
    Month 
    , AmntDue 
    , NumberOfBooksPurch  
    from (    
         select   year(order_date) as Year 
                , month(order_date) as Month
                ,  sum(quantity * order_price) as AmntDue    
                ,  count(order_id) as NumberOfBooksPurch    
                from a_bkorders.order_headers   
                join a_bkorders.order_details using (order_id)       
                group by Year, Month, order_id with rollup
         ) tbl;
    

    【讨论】:

    • 您知道我将如何继续进行相同的计算,仅显示年度总计的总行数吗?因此,每一年都与单独的年度总计分组。
    • 我不确定你的意思。更新您的问题并显示所需的输出。此外,如果您使用示例数据制作了一个 sqlfiddle,这将有所帮助。
    • 不确定如何在不重新排列格式的情况下在评论部分编辑查询。
    • 不要把它放在评论部分,使用您问题下方的edit链接添加它。
    猜你喜欢
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2011-09-29
    • 2010-11-04
    相关资源
    最近更新 更多