总收入的百分比

时间:2013-07-10 11:28:20

标签: sql oracle

我有类别,子类别和收入。

Category    Sub-Category    Revenue     Percentage
---------------------------------------------------------
Books       Text Books      5000        (5000/14000)*100
            Comics Books    6000
            Horror Books    3000

现在我的问题是,如何使用SQL实现这样的目标?

我需要百分比与该类别的总销售额相比。

3 个答案:

答案 0 :(得分:6)

Oracle具有RATIO_TO_REPORT分析函数,该函数计算值与一组值之和的比率。

select category, subcategory, revenue,
       round((ratio_to_report(revenue) over (partition by category) * 100),2) as percentage
from mytable;

输出:

CATEGORY  SUBCATEGORY  REVENUE  PERCENTAGE
-----------------------------------------
books     text         5000     35.71
books     horror       3000     21.43
books     comics       6000     42.86

示例小提琴here

答案 1 :(得分:2)

您可以使用analytical SUM function

select
  Category,
  SubCategory,
  Revenue,
  Revenue * 100 / sum(Revenue) over (partition by Category) as Percentage
from
  yourTable
;

答案 2 :(得分:1)

您可以使用子选择来获得总收入并在计算中使用它。

SELECT category, sub-category, revenue, 
((revenue / 
  SELECT sum(inne.revenue)
  FROM table inne
  WHERE inne.category = oute.category) * 100) AS percentage
FROM table oute