Oracle SQL - 简化总计列

时间:2014-07-17 15:06:16

标签: sql oracle

我有以下问题需要解决:

  1. 有没有办法简化Total列?
  2. 底行显示为null,我希望它也是“Total”。
  3. 以我的方式ROLLUP,ROLLUP((状态))更好吗?或者这与ROLLUP(状态)完全相同?
  4. 以下是我的询问:

    SELECT
            status AS "ROW LABELS",
            COUNT(case when source = 'INTERNET' THEN 1 end) AS "INTERNET",
            COUNT(case when source = 'SALES' THEN 1 end) AS "SALES",
            COUNT(case when source = 'REP' THEN 1 end) AS "REP",
            COUNT(case when source = 'COM' THEN 1 end) AS "COM",
            (COUNT(case when source = 'INTERNET' THEN 1 end) +
            COUNT(case when source = 'SALES' THEN 1 end) +
            COUNT(case when source = 'REP' THEN 1 end) +
            COUNT(case when source = 'COM' THEN 1 end)
            ) AS Total
    FROM
    SOMETABLE
    GROUP BY ROLLUP((status))
    order by 1;
    

    以下是我的数据:

    enter image description here

1 个答案:

答案 0 :(得分:2)

  1. 如果通过"简化"你的意思是"使计算更简洁"然后是。以下内容适用:

    COUNT(CASE WHEN source IN ('INTERNET', 'SALES', 'REP', 'COM') THEN 1 END)
    
  2. 只需使用nvl将NULL转换为值:NVL(status, 'TOTAL') AS row_labels

  3. ROLLUP( (status) )ROLLUP( status )

  4. 相同