Oracle中ROLLUP / Subtotals的特定文本

时间:2016-08-23 07:03:40

标签: sql oracle rollup

我有以下查询:

  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

2 个答案:

答案 0 :(得分:3)

您可以在第二列中替换您获得该标签的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;

如果您的nullERR_CODE列中包含REL_NR个值,则以下是更正确的方法:

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;

答案 1 :(得分:1)

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

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