gpt4 book ai didi

Oracle 计算涉及另一个计算的结果

转载 作者:行者123 更新时间:2023-12-01 09:39:59 24 4
gpt4 key购买 nike

首先,尽管我对 SQL 非常熟悉,但我完全是 Oracle 菜鸟。我有一个成本列。我需要计算总成本,总成本的百分比,然后是百分比的运行总和。我在百分比的运行总和方面遇到了麻烦,因为我能想到的唯一方法是使用嵌套的 SUM 函数,这是不允许的。

以下是有效的:

SELECT cost, SUM(cost) OVER() AS total, cost / SUM(cost) OVER() AS per
FROM my_table
ORDER BY cost DESC

这是我尝试做的但不起作用:

SELECT cost, SUM(cost) OVER() AS total, cost / SUM(cost) OVER() AS per,
SUM(cost/SUM(cost) OVER()) OVER(cost) AS per_sum
FROM my_table
ORDER BY cost DESC

我只是做错了,还是我试图做的事情不可能?顺便说一句,我使用的是 Oracle 10g。提前感谢您的帮助。

最佳答案

您不需要在该内联 View 中进行排序,尤其是因为外部选择正在按顺序进行排序。另外,cost/SUM(cost) OVER () 等于 RATIO_TO_REPORT(cost) OVER ()。

一个例子:

SQL> create table my_table(cost)
2 as
3 select 10 from dual union all
4 select 20 from dual union all
5 select 5 from dual union all
6 select 50 from dual union all
7 select 60 from dual union all
8 select 40 from dual union all
9 select 15 from dual
10 /

Table created.

您的初始查询:

SQL> SELECT cost, SUM(cost) OVER() AS total, cost / SUM(cost) OVER() AS per
2 FROM my_table
3 ORDER BY cost DESC
4 /

COST TOTAL PER
---------- ---------- ----------
60 200 .3
50 200 .25
40 200 .2
20 200 .1
15 200 .075
10 200 .05
5 200 .025

7 rows selected.

Quassnoi 的查询包含一个错字:

SQL> SELECT  cost, total, per, SUM(running) OVER (ORDER BY cost)
2 FROM (
3 SELECT cost, SUM(cost) OVER() AS total, cost / SUM(cost) OVER() AS per
4 FROM my_table
5 ORDER BY
6 cost DESC
7 )
8 /
SELECT cost, total, per, SUM(running) OVER (ORDER BY cost)
*
ERROR at line 1:
ORA-00904: "RUNNING": invalid identifier

如果我纠正了那个错字。它给出了正确的结果,但排序错误(我猜):

SQL> SELECT  cost, total, per, SUM(per) OVER (ORDER BY cost)
2 FROM (
3 SELECT cost, SUM(cost) OVER() AS total, cost / SUM(cost) OVER() AS per
4 FROM my_table
5 ORDER BY
6 cost DESC
7 )
8 /

COST TOTAL PER SUM(PER)OVER(ORDERBYCOST)
---------- ---------- ---------- -------------------------
5 200 .025 .025
10 200 .05 .075
15 200 .075 .15
20 200 .1 .25
40 200 .2 .45
50 200 .25 .7
60 200 .3 1

7 rows selected.

我想这就是你要找的那个:

SQL> select cost
2 , total
3 , per
4 , sum(per) over (order by cost desc)
5 from ( select cost
6 , sum(cost) over () total
7 , ratio_to_report(cost) over () per
8 from my_table
9 )
10 order by cost desc
11 /

COST TOTAL PER SUM(PER)OVER(ORDERBYCOSTDESC)
---------- ---------- ---------- -----------------------------
60 200 .3 .3
50 200 .25 .55
40 200 .2 .75
20 200 .1 .85
15 200 .075 .925
10 200 .05 .975
5 200 .025 1

7 rows selected.

问候,抢。

关于Oracle 计算涉及另一个计算的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/946438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com