Oracle中增量添加列组件

时间:2017-10-04 07:51:52

标签: sql oracle

如何在Oracle 11g中获得以下输出?

Subjects      Marks     add_marks      %marks
Maths 1        68      
Maths 2        50         118           45.73
Maths 3        60         178           68.99
Maths 4        80         258           100.00
-----------------------------------------------
Total          258

我无法特别为add_marks列编码。它的增量性质使事情复杂化。

1 个答案:

答案 0 :(得分:4)

使用SUM( ... ) OVER ( ORDER BY ... )分析函数:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name ( Subjects, Marks ) AS
SELECT 'Maths 1', 68 FROM DUAL UNION ALL
SELECT 'Maths 2', 50 FROM DUAL UNION ALL
SELECT 'Maths 3', 60 FROM DUAL UNION ALL
SELECT 'Maths 4', 80 FROM DUAL;

查询1

SELECT subjects,
       marks,
       SUM( marks ) OVER ( ORDER BY subjects ) AS add_marks,
       100 * SUM( marks ) OVER ( ORDER BY subjects ) / SUM ( MARKS ) OVER () AS "%marks"
FROM   table_name

<强> Results

| SUBJECTS | MARKS | ADD_MARKS |             %marks |
|----------|-------|-----------|--------------------|
|  Maths 1 |    68 |        68 | 26.356589147286822 |
|  Maths 2 |    50 |       118 | 45.736434108527135 |
|  Maths 3 |    60 |       178 |   68.9922480620155 |
|  Maths 4 |    80 |       258 |                100 |