Skip to content
Advertisement

running sum or cumulative frequency using subquery

Below is the output of cumulative frequency according to datewise, which I want to change into the subquery. The output is also correct but I want to do it by using a subquery.

OUTPUT

orderdate    totalsum   sum  
1996-07-04      27      27
1996-07-05      49      76
1996-07-08      101     177
1996-07-09      105     282
1996-07-10      102     384
1996-07-11      57      441

Advertisement

Answer

You would use window functions:

SELECT o.orderdate, SUM(od.quantity) AS totalsum,
       SUM(SUM(od.quantity)) OVER (ORDER BY o.orderdate) as runningsum
FROM orders o JOIN
     orderdetails od
     ON o.orderid = od.orderid
GROUP BY o.orderdate;

Not only is this simpler to write, but it should be significantly faster — and no CTE or subquery is appropriate for this version.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement