汇总功能和百分比值

时间:2017-09-27 00:31:55

标签: oracle rollup

我尝试使用ROLLUP函数显示表空间使用情况,结果看起来不错。但是,正如您所看到的,Total的percent_free只是一个总和而不是百分比。 你能帮我改变下面的查询来得到一个百分比值?

SELECT nvl(df.tablespace_name,'Total') TABLESPACE,
    sum(df.total_space_mb) TOTAL_SPACE_MB,
    sum((df.total_space_mb - fs.free_space_mb)) USED_SPACE_MB,
    sum(fs.free_space_mb) FREE_SPACE_MB,
    sum(ROUND(100 * (fs.free_space / df.total_space),2)) PERCENT_FREE
FROM (SELECT tablespace_name, SUM(bytes) TOTAL_SPACE,
   ROUND(SUM(bytes) / 1048576) TOTAL_SPACE_MB
   FROM dba_data_files
   GROUP BY tablespace_name) df,
  (SELECT tablespace_name, SUM(bytes) FREE_SPACE,
    ROUND(SUM(bytes) / 1048576) FREE_SPACE_MB
    FROM dba_free_space
    GROUP BY tablespace_name) fs
WHERE df.tablespace_name = fs.tablespace_name(+)
GROUP BY rollup(df.tablespace_name)
ORDER BY df.tablespace_name


TABLESPACE      TOTAL_SPACE_MB USED_SPACE_MB FREE_SPACE_MB PERCENT_FREE
--------------- -------------- ------------- ------------- ------------
DEMO                      1500            47          1453        96.87
NORMAL                      10             1             9        88.75
SYSAUX                    7990          7600           390         4.88
SYSTEM                     970           961             9           .9
UNDOTBS1                  1690            24          1666        98.57
USERS                     5275           964          4311        81.73
Total                    17435          9597          7838        371.7

1 个答案:

答案 0 :(得分:1)

您可以使用DECODE

DECODE(df.tablespace_name, NULL,
        ROUND(100*SUM(fs.FREE_SPACE)/SUM(df.total_space),2),
        SUM(ROUND(100 * (fs.free_space / df.total_space),2))) PERCENT_FREE,

当它是' Total' row(tablespace_name为null)对整个表使用舍入值。然后在DECODE的else子句中照常计算其他行。

SELECT nvl(df.tablespace_name,'Total') TABLESPACE,
    sum(df.total_space_mb) TOTAL_SPACE_MB,
    sum((df.total_space_mb - fs.free_space_mb)) USED_SPACE_MB,
    sum(fs.free_space_mb) FREE_SPACE_MB,
    DECODE(df.tablespace_name, NULL,
      ROUND(100*SUM(fs.FREE_SPACE)/SUM(df.total_space),2),
      SUM(ROUND(100 * (fs.free_space / df.total_space),2))) PERCENT_FREE
FROM (SELECT tablespace_name, SUM(bytes) TOTAL_SPACE,
   ROUND(SUM(bytes) / 1048576) TOTAL_SPACE_MB
   FROM dba_data_files
   GROUP BY tablespace_name) df,
  (SELECT tablespace_name, SUM(bytes) FREE_SPACE,
    ROUND(SUM(bytes) / 1048576) FREE_SPACE_MB
    FROM dba_free_space
    GROUP BY tablespace_name) fs
WHERE df.tablespace_name = fs.tablespace_name(+)
GROUP BY rollup(df.tablespace_name)
ORDER BY df.tablespace_name