0

我正在尝试将聚合函数列添加到现有结果集中。我尝试过 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

谢谢

4

1 回答 1

1

好像你在追求:

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

这仅取决于您需要分区的内容。根据样本数据, attr 应该足够了;但我可能会看到 ID 和 attr。

例子:

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 |
+----+-------+-------+------------------------------------------+
于 2018-03-12T14:28:48.113 回答