Oracle RATIO_TO_REPORT和Rollup

时间:2012-04-17 17:44:53

标签: sql oracle

SELECT HOME_DEPT, LINECODE, SUM(TOTAL_HRS),  
       TO_CHAR ( 
       100*RATIO_TO_REPORT(SUM(TOTAL_HRS))
       OVER (PARTITION BY HOME_DEPT), 
       '990.00L', 'NLS_CURRENCY=%'
       ) PCT_JOB
       FROM TABLE 
       GROUP BY HOME_DEPT, LINECODE ORDER BY HOME_DEPT ASC, PCT_JOB DESC;

上述Oracle查询的工作原理如下:

DEPT1 LINECODE1 100 50% 
DEPT1 LINECODE2  50 25%
DEPT1 LINECODE3  50 25%

DEPT2 LINECODE1  20 12.5% 
DEPT2 LINECODE2  20 12.5%
DEPT2 LINECODE3  20 12.5%
DEPT2 LINECODE4  20 12.5%
DEPT2 LINECODE5  20 12.5%
DEPT2 LINECODE6  20 12.5%
DEPT2 LINECODE7  20 12.5%
DEPT2 LINECODE8  20 12.5%

现在我想按部门汇总以获得结果:

DEPT1 LINECODE1 100  50% 
DEPT1 LINECODE2  50  25%
DEPT1 LINECODE3  50  25%
DEPT1           200 100%  <--- desired

DEPT2 LINECODE1  20  12.5% 
DEPT2 LINECODE2  20  12.5%
DEPT2 LINECODE3  20  12.5%
DEPT2 LINECODE4  20  12.5%
DEPT2 LINECODE5  20  12.5%
DEPT2 LINECODE6  20  12.5%
DEPT2 LINECODE7  20  12.5%
DEPT2 LINECODE8  20  12.5%
DEPT2           160 100.0%    <--- desired

我尝试过各种各样的东西,例如GROUPING SETS但是我的PCT_JOB值是错误的。

2 个答案:

答案 0 :(得分:5)

GROUPING函数documented here。此函数将告诉您给定行是否为“超级聚合”行。然后,您可以根据该行的值进行订购。

请注意,我对PCT_JOB列的定义有点像kludge,因为我分别对正常行和“超级聚合”行进行分组。

下面的SQL查询应该可以满足您的需求。

select
  home_dept,
  linecode,
  total_hrs,
  to_char(
    100 * ratio_to_report(total_hrs) over (partition by home_dept, linecode_group),
    '990.00L', 'NLS_CURRENCY=%') as pct_job 
from (
  SELECT 
    HOME_DEPT, 
    LINECODE, 
    SUM(TOTAL_HRS) as total_hrs, 
    grouping(linecode) as linecode_group
  FROM my_TABLE 
  GROUP BY grouping sets ((home_dept), (HOME_DEPT, LINECODE))
)
ORDER BY HOME_DEPT ASC, linecode_group, pct_job desc

另外,我在这里使用了分组集,但是可以使用:

  GROUP BY home_dept, rollup(LINECODE)

SQLFiddle is available,可以让你看到一个例子。

答案 1 :(得分:3)

这是一个不需要外部查询的答案。它基于Mike Meyers&#39;回答,但现在行代码的GROUPING在PARTITION BY子句中指定,也在ORDER BY子句中指定:

SELECT
    home_dept,
    linecode,
    SUM(total_hrs) AS total_hrs, 
    TO_CHAR(100 * RATIO_TO_REPORT (SUM(total_hrs))
            OVER (PARTITION BY home_dept, GROUPING(linecode)),
            '990.00L', 'NLS_CURRENCY=%') AS pct_job
FROM my_table
GROUP BY GROUPING SETS ((home_dept), (home_dept, linecode))
ORDER BY home_dept, GROUPING(linecode), pct_job DESC

以上代码使用GROUP BY GROUPING SETS,但以下GROUP BY也可以使用:

GROUP BY home_dept, ROLLUP(linecode)

另外FYI:原始问题要求线路编码按其百分比的降序排序,而不是按行代码值(即线路代码名称)排序....但在给定的示例中,&#34的结果按百分比降序&# 34;看起来像&#34;按名称提升。&#34;如果有人想按名称按升序查看行代码而不考虑百分比,则可以将ORDER BY行更改为:

ORDER BY home_dept, linecode