CodexBloom - Programming Q&A Platform

T-SQL Calculating Running Total with Different Grouping Criteria in SQL Server 2022

πŸ‘€ Views: 42 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-17
sql-server t-sql window-functions T-SQL

I'm trying to calculate a running total in T-SQL that resets based on a different grouping criterion, but I'm getting unexpected results. Specifically, I want to calculate a running total of sales per product category, and the running total should reset when the category changes. I'm using SQL Server 2022 and have the following table structure: ```sql CREATE TABLE Sales ( SaleID INT PRIMARY KEY, ProductID INT, CategoryID INT, SaleDate DATE, Amount DECIMAL(10, 2) ); ``` I attempted to achieve this with a CTE and a `SUM` window function, but the results don’t seem to reset at the right times. Here’s my query: ```sql WITH CTE AS ( SELECT SaleID, CategoryID, SaleDate, Amount, SUM(Amount) OVER (PARTITION BY CategoryID ORDER BY SaleDate ROWS UNBOUNDED PRECEDING) AS RunningTotal FROM Sales ) SELECT * FROM CTE; ``` When I run this, I get a continuous running total for all categories instead. For example, if Category 1 has sales of 100 and 200 on two different dates, the running total shows 100, 300 instead of resetting back to 100 on the new category. I've tried adjusting the `ORDER BY` clause, but it didn't help. What am I missing to ensure the running total resets correctly upon category change? Any advice or insight would be greatly appreciated!