T-SQL -RANGE VALUE GENERATION

BHVS 61 Reputation points
2022-03-29T17:20:03.867+00:00

Hi All,188000-source-data.png188053-finaloutput.png

I have a requirement to generate Range sales like below.

Thanks in Advance...

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

Answer accepted by question author
  1. LiHong-MSFT 10,061 Reputation points
    2022-03-30T08:42:23.987+00:00

    Hi @BHVS
    Check this query:

     create table #test  
     (  
     PRODUCT varchar(10),  
     SALES int,  
     VALUE int  
     )  
     insert into #test values  
     ('PRD1',10,1),('PRD1',20,1),('PRD1',40,1),('PRD1',15,-1),('PRD1',23,-1),('PRD1',14,-1),  
     ('PRD1',21,1),('PRD1',29,1),('PRD1',33,1),('PRD1',17,-1),('PRD1',26,-1),('PRD1',22,-1),  
     ('PRD2',11,1),('PRD2',13,1),('PRD2',22,-1),('PRD2',28,-1)  
          
     ;WITH CTE1 AS  
     (  
      SELECT *,CASE WHEN VALUE = LAG(VALUE)OVER(ORDER BY PRODUCT) THEN 0 ELSE 1 END AS TO_SUM  
      FROM #test  
     ),CTE2 AS  
     (  
      SELECT *,SUM(TO_SUM)OVER(ORDER BY PRODUCT ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS PART  
      FROM CTE1  
     ),CTE3 AS  
     (  
      SELECT *,SUM(SALES)OVER(PARTITION BY PART ORDER BY PRODUCT ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)AS RANGE_END  
      FROM CTE2  
     )  
     SELECT PRODUCT,SALES,VALUE,CAST((LAG(RANGE_END,1,0)OVER(PARTITION BY PART ORDER BY PRODUCT)+1)AS VARCHAR(10))+' - '+CAST(RANGE_END AS VARCHAR(10))AS [FINAL SALES RANGES]  
     FROM CTE3  
    

    Best regards,
    LiHong

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 47,581 Reputation points
    2022-03-30T06:39:59.397+00:00

    I have a requirement to generate Range sales like below.

    And now we have to guess the logic for it?

    That's really to less on information. Please post table design as DDL, some sample data as DML statement and the expected result.


Your answer

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