Search code examples
sql-server-2008cursor

how to make constant value in MSSQL without cursor


I have one table that I will loop without cursor in MSSQL.

Unit    Speed     C           Count         x      y
A     | 200     | 200       | 3           |   3  | 0
A     | 230     | 230       | 4           |   7  | 0
A     | 240     | 240       | 3           |  10  | 0
A     | 250     | 255       | 2           | >=12 | 5
A     | 260     | 255       | 2           |   2  | 0
A     | 270     | 255       | 2           |   4  | 0
A     | 280     | 255       | 3           |   7  | 0
A     | 290     | 255       | 4           |   11 | 0
A     | 300     | 260       | 2           | >=12 | 5
A     | 310     | 260       | 2           |   2  | 0
A     | 320     | 260       | 2           |   4  | 0
A     | 340     | 260       | 2           |   6  | 0


How to make C value is constant (speed + 5 for first record and C + 5 for next value) after summary of X value is equal or same with 12?

I want to loop the record without cursor (because if I use cursor, database will be deadlocked).


Solution

  • With a little help from common table expressions and some window functions I came up with the following solution. Note that you need some column to sort the table.

    With cte AS 
    (
    SELECT RowOrder
          ,cCount
          ,SUM(cCount) OVER(order by RowOrder) As SumcCount
    
    FROM Tbl
    )
    
    SELECT RowOrder
          ,cCount
          ,SumcCount % 12 as x
          ,CASE WHEN SumcCount >= 12 
           AND RANK() OVER (Partition by SumcCount / 12 ORDER BY RowOrder) = 1 THEN
               5
           ELSE
               0
           END As y   
    FROM CTE
    ORDER BY RowOrder
    

    Explanations:

    • Common table expressions is a way to create temporary result sets.
    • using the SUM function with the OVER clause allows for cumulative sums on cCount (i didn't want to use count since it's a reserved word).
    • using the RANK function gave me a simple way to determine if the cumulative sum of cCount equals to any multiplication of 12 or more. note that in the case there is also a condition that the cumulative sum of cCount is 12 or more.