Oracle 在结果行上添加组函数

Oracle add group function over result rows

我正在尝试将聚合函数列添加到现有结果集中。我已经尝试过 OVER()、UNION 的变体,但找不到解决方案。

当前结果集示例:

ID     ATTR     VALUE
1      score     5
1      score     7
1      score     9

示例所需结果集:

ID     ATTR     VALUE   STDDEV (score)
1      score     5       2
1      score     7       2
1      score     9       2

谢谢

你似乎在追求:

  • stddev(value) over (partition by attr)
  • stddev(value) over (partition by id, attr)

这取决于您需要根据什么进行分区。根据示例数据,attr 应该足够了;但我可能会看到 ID 和属性。

示例:

With CTE (ID, Attr, Value) as (
SELECT 1, 'score', 5 from dual union all
SELECT 1, 'score', 7 from dual union all
SELECT 1, 'score', 9 from dual union all 
SELECT 1, 'Z', 1 from dual union all
SELECT 1, 'Z', 5 from dual union all
SELECT 1, 'Z', 8 from dual)

SELECT A.*, stddev(value) over (partition by attr)  
FROM cte A
ORDER BY attr, value

DOCS 表明通过在解析中添加一个 order by,可以获得每条记录的累积标准偏差。

给我们:

+----+-------+-------+------------------------------------------+
| ID | attr  | value |                  stdev                   |
+----+-------+-------+------------------------------------------+
|  1 | Z     |     1 | 3.51188458428424628280046822063322249225 |
|  1 | Z     |     5 | 3.51188458428424628280046822063322249225 |
|  1 | Z     |     8 | 3.51188458428424628280046822063322249225 |
|  1 | score |     5 |                                        2 |
|  1 | score |     7 |                                        2 |
|  1 | score |     9 |                                        2 |
+----+-------+-------+------------------------------------------+