Order By In SQL Cursor
I am trying to insert cumulative value (CV) into a column using cursor. I would like to calculate cumulative value (CV) order by a date (DT) column. Example: CREATE TABLE #unsorted
Solution 1:
You can use SUM() with OVER() to generate cumulative totals. In this particular case :
select ID, DT, sum(id) over(order by dt) AS CV
from unsorted
order by dt
Produces :
3 2017-01-01 3
2 2018-12-15 5
1 2019-01-01 6
OVER() and analytic functions like LAG and LEAD can solve many problems that required cursors or complex solutions in the past. For example, LAG() OVER... can be used to find the difference between the current row in an ordered result set and the previous one, or detect value changes, making it easier to find ranges or gaps in a sequence
Post a Comment for "Order By In SQL Cursor"