get no of quantity from sql table

RAVI 916 Reputation points
2022-04-05T07:55:51.433+00:00

Hello
This is my sql resultset data

189969-image.png

I want like this out put how to do so

189970-image.png

Thank You

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,282 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,774 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,555 questions
{count} votes

Accepted answer
  1. Jingyang Li 5,891 Reputation points
    2022-04-06T02:00:32.56+00:00

    DECLARE @Products TABLE (
    ORDERNO INT, RefNO int, Size int, quantity int)
    INSERT INTO @Products(ORDERNO, RefNO, Size, quantity)
    VALUES ( 26, 1, 7,20),(26, 2, 7,10),(27,4, 8,40)

    ;with mycte as (
    SELECT a.ORDERNO,a.RefNO,a.Size,a.quantity, (
    SELECT SUM(b.quantity)
    FROM @Products b WHERE a.ORDERNO=b.ORDERNO
    AND b.RefNO <= a.RefNO) AS runningTotal
    ,row_number() over(partition by ORDERNO order by RefNO ) rn
    FROM @Products AS a
    )

    Select m1.ORDERNO,m1.RefNO,m1.Size,m1.quantity,
    Case when m1.rn=1 then '01-'+Cast(m1.quantity as varchar(10))
    else Cast(m2.runningTotal+1 as varchar(10))+'-'+Cast(m1.runningTotal+1 as varchar(10)) end NoOfQuantity
    from mycte m1
    left join mycte m2 on m1.ORDERNO=m2.ORDERNO
    and m1.rn=m2.rn+1
    ORDER BY m1.ORDERNO,m1.RefNO;

    /*
    ORDERNO RefNO Size quantity NoOfQuantity
    26 1 7 20 01-20
    26 2 7 10 21-31
    27 4 8 40 01-40

    */

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. LiHong-MSFT 10,046 Reputation points
    2022-04-05T08:58:51.237+00:00

    Hi @RAVI
    Check this query:

    ;WITH CTE AS  
    (  
     SELECT ORDERNO,Ref_No,SIZE,Quantity  
            ,LAG(Quantity,1,0)OVER(PARTITION BY ORDERNO,SIZE ORDER BY Ref_No)+1 AS Range_Start  
            ,SUM(Quantity)OVER(PARTITION BY ORDERNO,SIZE ORDER BY Ref_No ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)AS Range_End  
     FROM Your_Table  
    )  
    SELECT ORDERNO,Ref_No,SIZE,Quantity  
          ,CAST(Range_Start AS VARCHAR(30))+'-'+CAST(Range_End AS VARCHAR(30)) AS [No Of Quantity]  
    FROM CTE  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly 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 comments No comments

  2. RAVI 916 Reputation points
    2022-04-05T09:21:35.097+00:00

    can i get this sql code using old version like sql 2008
    thanks