-1

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

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

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

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

4

3 回答 3

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

样品小提琴在这里

于 2013-07-10T12:08:41.343 回答
2

您可以使用分析 SUM 函数

select
  Category,
  SubCategory,
  Revenue,
  Revenue * 100 / sum(Revenue) over (partition by Category) as Percentage
from
  yourTable
;
于 2013-07-10T11:31:45.947 回答
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
于 2013-07-10T11:32:06.160 回答