Group By and Running Total and Totals using SQL Query

Malam Malam 266 Reputation points
2025-04-15T23:06:35.75+00:00

My sql query returns the following values. How do I

  1. Group By 2. Add Running Total 3. Add Total

to get it done as shown in pictured example 1, 2 and 3 below?

User's image

I need 3 queries to get the following results:

1: put it in Group By to show as

User's image

2: Add a column to return Running Total as

User's image

3: Add a Total for each Group

User's image

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.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Viorel 125.8K Reputation points
    2025-04-16T02:11:50.04+00:00

    Check the query for the third problem:

    select *, 
        sum(Price) over (partition by Category, Unit order by SerialNo) as RunningTotal,
        case when lead(SerialNo) over (partition by Category, Unit order by SerialNo) is null 
        then cast(sum(Price) over (partition by Category, Unit) as varchar(max)) else '' end as TotalValue 
    from MyTable
    order by Category, Unit, SerialNo
    

0 additional answers

Sort by: Most helpful

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.