首页 > 解决方案 > Oracle SQL:使用 SUM OVER PARTITION 更新表

问题描述

我一直在尝试执行以下操作:

CREATE TABLE T_example
(category number(1,0),
amount number(4,0),
amount2 number(4,0))

INSERT INTO T_example VALUES (1,20,40);
INSERT INTO T_example VALUES (1,30,40);
INSERT INTO T_example VALUES (2,5,60);
INSERT INTO T_example VALUES (2,15,60);
INSERT INTO T_example VALUES (2,30,60);

如您所见,所有行在其类别中都包含相同的数量2。现在我想根据金额与类别的分布在每个类别中分配amount2。

UPDATE T_example
SET amount2 = amount2 * amount / SUM(amount) OVER (PARTITION BY category ORDER BY category); 

我想得到:

category - amount - amount2
1 - 20 - 16
1 - 30 - 24
2 - 5 - 6
2 - 15 - 18
2 - 30 - 36

但是代码不起作用。它说:

00934.00000 - “此处不允许使用群组功能”

你能告诉我我哪里错了吗?

标签: sqloraclesumwindow-functions

解决方案


我认为下面会为你工作,共同相关的子查询

 UPDATE T_example t1
    SET t1.amount2 = (t1.amount*t1.amount2) / (

       select sum(amount) from -- from was missing
      T_example t2 where t2.category=t1.category
      group by category

            ); 

https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=e2c00fe7ad8866bb4a62f66b08133f95

CATEGORY    AMOUNT  AMOUNT2
1            20     16
1            30     24
2             5     6
2            15     18
2            30     36

推荐阅读