Oracle 中 ROLLUP/Subtotals 的特定文本

Specific text to ROLLUP / Subtotals in Oracle

我有以下查询:

  SELECT REL_NR, ERR_CODE, COUNT (ERR_CODE)
  FROM ZDL_ERR
  WHERE ERR_CODE > 0
  GROUP BY ROLLUP (REL_NR, ERR_CODE)
  ORDER BY REL_NR DESC, ERR_CODE;

具有以下输出:

196 1148   16
196 1180 2288
196 1181  177
196      2481

有没有办法给 ROLLUP 一个文本,使其显示如下:

196 1148   16
196 1180 2288
196 1181  177
Subtotal 2481

您应该使用 GROUPING 子句。代码将如下所示:

SELECT DECODE(GROUPING(REL_NR),0,TO_CHAR(REL_NR),'Subtotal') REL_NR ...

您可以替换您在第二列中获得该标签的 null 值:

SELECT   REL_NR, 
         COALESCE(TO_CHAR(ERR_CODE), 
           CASE WHEN REL_NR IS NULL THEN 'Grand Total'
                                    ELSE 'Sub Total'
           END) AS ERR_CODE,
         COUNT (ERR_CODE)
FROM     ZDL_ERR
WHERE    ERR_CODE > 0
GROUP BY ROLLUP (REL_NR, ERR_CODE)
ORDER BY REL_NR, ERR_CODE;

如果您的 ERR_CODEREL_NR 列中有 null 个值,则以下是更正确的方法:

SELECT   REL_NR,
         CASE GROUPING(ERR_CODE) 
             WHEN 1 THEN 
                 CASE GROUPING(REL_NR)
                     WHEN 1 THEN 'Grand Total'
                            ELSE 'Sub Total'
                 END
             ELSE TO_CHAR(ERR_CODE)
         END AS ERR_CODE,
         COUNT (ERR_CODE)
FROM     ZDL_ERR
WHERE    ERR_CODE > 0
GROUP BY ROLLUP (REL_NR, ERR_CODE)
ORDER BY REL_NR, ERR_CODE;