WITH ROLLUP无法正常工作

时间:2014-05-04 00:07:34

标签: mysql database rollup

这里我显示第一列中订单的年份,第二列中的月份,第三列中的Order_id。我希望按月,按年和总计显示总数。

这是我试图获得的结果:

enter image description here

月总数,年总数和总计。

这是我的疑问:

SELECT coalesce(extract(year FROM order_date), 'Grand Total') as 'Year'
    , CASE  when extract(year FROM order_date) is null then ' '
        when extract(month FROM order_date) is null then 'Year total'
        else extract(month FROM order_date)
    END as `Month`
    , CASE when extract(month FROM order_date) is null Then ' '
        else coalesce(oh.order_id, 'Month Total')
    END as 'Order ID'
    , sum(quantity * order_price) AS 'AmntDue'
    , sum(quantity) AS 'NumBooksPurch'
FROM a_bkorders.order_headers oh
JOIN a_bkorders.order_details od on oh.order_id = od.order_id
GROUP BY extract(year FROM order_date), extract(month FROM order_date), oh.order_id with rollup
;

但这就是我得到的:

enter image description here

月份总数似乎工作正常但不是年度总数或总计。我无法理解我做错了什么。

1 个答案:

答案 0 :(得分:2)

我无法保证这会有效,因为我没有所有的数据(也就是第二张表中的订单金额)..但我觉得这样的事情会起作用。让我知道它是不是搞砸了。

SELECT
    Year, 
    IF(Year = 'Grand Total', ' ', Month), 
    IF(Month = 'Year Total' OR Year = 'Grand Total', ' ', Ordered_ID),
    AmntDue, 
    NumberOfBooksPurch 
FROM(
    SELECT
        COALESCE(Year, 'Grand Total') AS Year,
        CASE 
            WHEN Year IS NULL THEN ' ' 
            ELSE COALESCE(MONTH, 'Year Total') 
        END AS Month,
        Ordered_ID,
        AmntDue, 
        NumberOfBooksPurch
    FROM (
        SELECT   
            YEAR(order_date) AS Year, 
            MONTH(order_date) AS Month,
            CASE 
                WHEN MONTH(order_date) IS NULL THEN ' '
                ELSE COALESCE(order_id, 'Month Total')
            END as Ordered_ID,
            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
    ) temp_table_alias
) final_temp_table;