TechAid24

Your Technical Consultant

Counting sql rows, adding value of every row to the next

Posted on by Selim Ahmed 1 minute read

Hello Everyone! In this article, we want to discuss a nice function of adding the value of every row to the next in SQL Server. Before we get started, if you want to know about using multiple columns with “Not In”, please go through the following article: SQL: Can you use multiple columns for NOT IN.

Sometimes we need to select data with the auto-generated sequence “Serial No” from the table. It may have an auto-generated column in your table. But when you select data with some condition, the column is may not be sequential. Then what you do?? It’s very simple to generate an auto-sequential number with “ROW_NUMBER()“.

Please see the table structure first:

Query to show adding value of every row to the next

With cte_Test(Sequence,PartNO,Whole)
As
(
      SELECT ROW_NUMBER() OVER(ORDER BY Dealer) AS 'Sequence' ,PartNO,Whole FROM ATable
)

SELECT t1.PartNO,SUM(T2.Whole) AS Value FROM cte_Test t1
CROSS JOIN cte_Test t2 where t2.Sequence <= t1.Sequence
GROUP BY t1.PartNO
ORDER BY 2

You can use the query also,

SELECT t1.PartNO,SUM(T2.Whole) AS Value FROM ATable t1
CROSS JOIN ATable t2 where t2.SerialNo <= t1.SerialNo
GROUP BY t1.PartNO
ORDER BY 2
adding value of every row to the next

Tags:

Selim Ahmed

Thank you for visiting my personal blog. I’m Selim Ahmed, a tech-savvy who loves to learn a new technology every day. Innovation, research, and development is my daily activities. I love to work in a place where I can learn, innovate, and develop new things.Please feel free to reach me on any comments and feedback you have. I would be more than glad to listen and reply.

Leave a Reply

Your email address will not be published. Required fields are marked *