ROLL UP 仅保留总计并删除小计

ROLL UP to keep only Grand Total and remove sub totals

我对以下查询输出有 2 个问题:


    COALESCE(Division,'Grand Total') Divi,
    COALESCE(Section,'DivTotal') Sec,
    COALESCE(m.Department,'SecTotal') Dept,
    COALESCE(Assortment,'DeptTotal') Assort,
    COALESCE(Promo,'') Prom,
    COALESCE(Range_Details,'') Range_,
    SUM(`WH STK`) WH_STK,
    SUM(`AL STK QTY`) AL_STK,
    SUM(`AL SAL QTY`) AL_SAL,
    SUM(`AL LYa`) LY_a,
    SUM(`AL LYb`) LY_b,
    SUM(`AL MIN`) AL_MIN,
    b.LYa_tot,
    b.LYb_tot,
    COALESCE(ROUND(((SELECT b.LYb_tot)/(SELECT b.LYa_tot))* COALESCE(SUM(`AL SAL QTY`),0),0),0) 'upcoming',
    COALESCE((ROUND(((SELECT b.LYb_tot)/(SELECT b.LYa_tot))*SUM(`AL SAL QTY`),0) +  SUM(`AL MIN`)) - SUM(`AL STK QTY`),0) 'Dispatch'

FROM
(.....I have removed rest of the query part to make it short....) m
GROUP BY
    m.Division,
    m.Section,
    m.Department,
    m.Assortment,
    m.Promo,
    m.Range_Details WITH ROLLUP HAVING
(Division IS NOT NULL AND Section IS NOT NULL AND Department IS NULL AND Assortment IS NULL AND Promo IS NULL AND Range_Details IS NULL )
OR (Division IS NOT NULL AND Section IS NOT NULL and Section NOT IN  ('OTHERS','W_ACCESSORIES','W_BOTTOMWEAR','W_INNERWEAR','W_UPPERWEAR') AND Department IS NOT NULL AND Assortment IS NULL AND Promo IS NULL AND Range_Details IS NULL )
OR (Division IS NOT NULL AND Section NOT IN  ('OTHERS','W_ACCESSORIES','W_BOTTOMWEAR','W_INNERWEAR','W_UPPERWEAR') AND Department IS NOT NULL and Department NOT IN ('GLOVE','RAINCOAT','SWIM SUIT','CORD TROUSERS','COTTON TROUSERS','FORMAL TROUSERS') AND Assortment IS NOT NULL AND Promo IS not NULL AND Range_Details IS not NULL )
OR (Division IS NULL AND Section IS NULL AND Department IS NULL AND Assortment IS NULL AND Promo IS NULL AND Range_Details IS NULL )

enter image description here 1.) 如何只保留最后一行的 'Grand Total' 并删除 'DivTotal'、'SecTotal'、'DeptTotal'.

2.) 有没有更好的选择来使用“WITH ROLLUP”,这样我就可以只选择需要小计的列,而不是对 GROUP BY 子句中的所有列进行小计?

注意:我已经在使用多个 UNION,所以如果可能请给出没有 union 的解决方案。 无法嵌入图片,给您带来的不便深表歉意。

我认为 CTE 和摘要可能是更简单的方法:

with cte as (
      select m.Division, m.Section, m.Department, m.Assortment,  m.Promo, m.Range_Details,
             . . . 
      from . . .
      group by m.Division, m.Section, m.Department, m.Assortment,  m.Promo, m.Range_Details
     )
select *
from cte
union all
select 'Grand Total', null, null, null, null, null,
       sum(WH_STK), . . . 
from cte;

我是这样解决的,灵感来自Whosebug本身的一个答案:

COALESCE(Division,'Grand Total') Divi,
(CASE WHEN Division IS NOT NULL THEN COALESCE(Section,'DivTotal') ELSE '' END) Sec,
(CASE WHEN Section IS NOT NULL THEN COALESCE(m.Department,'SecTotal') ELSE '' END) Dept,
(CASE WHEN m.Department IS NOT NULL THEN COALESCE(Assortment,' Total') ELSE '' END) Assort,
COALESCE(Promo,'') Prom,
(CASE WHEN Division IS NULL  THEN COALESCE(Range_Details,'Grand Total') ELSE COALESCE(Range_Details,'') END) Range_

感谢大家抽出时间。