I am bit stuck with this not getting how do i proceed further
Assume I have below data in table
Note : All the below column fields [NAME , AGE , COURSE , MARKS
] are set to VARCHAR2(50 CHAR)
NAME | AGE | COURSE | MARKS A1 | ABC | MCA | 5 B1 | XYZ | MBA | 10 C1 | PQR | MMS | 14 D1 | YST | CAT | 18
Using below query I am able to get incremental sum , but not able to apply logic how to get incremental average
My Query :
select c1.* , SUM(MARKS) Over (Order by c1.NAME) AS CUM_COUNT from EMP c1 order by c1.NAME ASC;
Expected output :
NAME | AGE | COURSE | MARKS | CUM_COUNT | AVGS_CNT | A1 | ABC | MCA | 5 | 5 | 5/1 = 5 | B1 | XYZ | MBA | 10 | 15 | 15/2 = 7.5 | C1 | PQR | MMS | 14 | 29 | 29/3 = 9.6 | D1 | YST | CAT | 18 | 47 | 47/4 = 11.75 |
Solution in oracle OR python appreciated
Note : I have date in Oracle
The reason behind asking this question as it was asked to me in interview
Advertisement
Answer
To complement @mathguy’s answer, here the full query you need:
select e.*, sum(marks) over(order by name) as cum_count, 1.0 * sum(marks) over(order by name) / count(*) over(order by name) as avgs_cnt from emp e
Result:
NAME AGE COURSE MARKS CUM_COUNT AVGS_CNT ----- ---- ------- ------ ---------- ---------------- A1 ABC MCA 5 5 5 B1 XYZ MBA 10 15 7.5 C1 PQR MMS 14 29 9.66666666666667 D1 YST CAT 18 47 11.75
It uses windows functions by qualifying SUM()
and COUNT(*)
with OVER(ORDER BY NAME)
.
See running example at db<>fiddle.