Conditional Running Total sql

Mayur 41 Reputation points
2022-03-23T02:29:22.49+00:00

Hello there,

Below is my source dataset

Date Rejection Days
1/1/2018 0 10
2/1/2018 0 10
3/1/2018 0 10
4/1/2018 1 10
5/1/2018 0 10
6/1/2018 0 10
7/1/2018 2 10
8/1/2018 1 10
9/1/2018 0 10
10/1/2018 0 10
11/1/2018 0 10
12/1/2018 1 10

Running total calculation requirement :

  1. calculate running total as rejections are 0
  2. once we get rejection divide days by rejection + 1 and reset counter for running total and apply (divide days by rejection + 1 ) to next row
  3. repeat both step until we reach last reporting date

Expected result with manual excel formula/calculation.
185876-image.png

186246-image.png

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,787 questions
Azure Data Lake Analytics
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
0 comments No comments
{count} votes

Accepted answer
  1. Isabellaz-1451 3,616 Reputation points
    2022-03-23T06:56:58.493+00:00

    Hi @Mayur
    You can create a temptable ,then use CURSOR and store each row into the temptable,please check :

     DROP TABLE RESULTTABLE  
     CREATE TABLE RESULTTABLE  
    (Datestr varchar(20),  
    Rejection int,  
    Days int,  
    RUNNINGTOTAL int  
    )  
      
      
     DECLARE @DATESTR VARCHAR(20)  
     DECLARE @REJECTION INT  
     DECLARE @DAYS INT  
      
     DECLARE @SUM INT =0  
      
      
     DECLARE db_cursor CURSOR FOR   
    SELECT Datestr,Rejection, Days  
    FROM TEMPTABLE   
      
    OPEN db_cursor    
    FETCH NEXT FROM db_cursor INTO @DATESTR,@REJECTION,  @DAYS  
      
    WHILE @@FETCH_STATUS = 0    
    BEGIN    
          IF @REJECTION = 0  
    	  BEGIN  
             SET @SUM = @SUM+@DAYS  
    	  END  
    	  ELSE   
    	  BEGIN  
    	    SET @SUM =@DAYS/(@REJECTION+1)  
    	  END  
    	  INSERT INTO RESULTTABLE   
    	  SELECT @DATESTR,@REJECTION,@DAYS,@SUM  
      
          FETCH NEXT FROM db_cursor INTO @DATESTR,@REJECTION,  @DAYS  
    END   
      
    CLOSE db_cursor    
    DEALLOCATE db_cursor   
      
      
    SELECT * FROM RESULTTABLE  
    

    Result:

    185967-image.png

    Best Regards,
    Isabella


    If the answer is the right solution, please click "Accept Answer" and upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.