Oracle里的ratio_to_report函数

Oracle里的ratio_to_report函数

简要

RATIO_TO_REPORT是一个分析函数,用于计算某一列的值在指定分组中的所占的比率。

RATIO_TO_REPORT(col) over ([partition by xxx]) ; 
  • col:需要查询的列,如果该值为空,则比率的值也为空。
  • [partition by xxx]:指定的分组,如果省略该子句,则会计算当前值占指定分组中所有值的比率。
  • over的功能跟窗口函数是一样的

实例

计算个人成绩,占总成绩的占比。

select t.*, ratio_to_report(score) over() from temp t 
Oracle MySQL

指定分组。计算个人成绩,占各班级总成绩的占比。

select t.*, ratio_to_report(score) over(partition by class) from temp t 

在这里插入图片描述
下面就是不指定分组,但添加限制条件的情况。相当于对上面的结果进行拆分。

使用MySQL的写法

SELECT t.id,t.name,t.class,t.score,t.total_score,score/total_score FROM 
(
SELECT a.id,a.name,a.class,a.score,b.total_score 
FROM temp a, (SELECT SUM(score) AS total_score FROM temp WHERE class=3) b
WHERE a.class=3
) t
SELECT t.id,t.name,t.class,t.score,t.total_score,score/total_score FROM 
(
SELECT a.id,a.name,a.class,a.score,b.total_score 
FROM temp a, (SELECT SUM(score) AS total_score FROM temp) b 
) t

猜你喜欢

转载自blog.csdn.net/qq_55342245/article/details/127925047