我有一张这样的表:
ITEM_SALES
ITEM_NAME SALES
Item_name_1 5000
...
Item_name_x 3
我想得到的是获得代表销售额前50%的商品。因此,例如,如果总销售额为10,000,则仅使用item_name_1将占销售额的50%。
我显然可以通过以下方式获得总销售额:
select sum(sales) from ITEM_SALES.
...然后除以2得到50%的销售额。
但是,我不知道如何从那里获得代表50%销售额的顶级商品。
答案 0 :(得分:1)
您可以使用分析函数执行此操作:
select s.*
from (select item_name, sum(sales) as sumsales,
sum(sum(sales)) over (order by sum(sales) desc) as cumesales,
sum(sum(sales)) over () as totsales,
from item_sales
group by item_name
) s
where (cumesales - sumsales) < 0.5 * totsales;
子查询计算每个项目的销售额,以及另外两个值:
where
子句然后获取项目并包括通过50%阈值的项目。
答案 1 :(得分:1)
Oracle安装程序:
CREATE TABLE ITEM_SALES ( ITEM_NAME, SALES ) AS
SELECT 'item_name_' || LEVEL, 50 - 3 * (LEVEL - 1)
FROM DUAL
CONNECT BY LEVEL <= 16;
<强>查询强>:
SELECT *
FROM (
SELECT ITEM_NAME,
SALES,
SUM( SALES ) OVER ( ORDER BY SALES DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS cumulative_sales,
SUM( SALES ) OVER ( ORDER BY SALES DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING ) AS total_sales
FROM ITEM_SALES
)
WHERE cumulative_sales <= total_sales/2;
<强>结果:
ITEM_NAME SALES CUMULATIVE_SALES TOTAL_SALES
------------ ----- ---------------- -----------
item_name_1 50 50 440
item_name_2 47 97 440
item_name_3 44 141 440
item_name_4 41 182 440
item_name_5 38 220 440