I have table with departments. I need to count how many people are within which dept. This is easily done by
SELECT DEPT,
COUNT(*) as 'Total'
FROM SR
GROUP BY DEPT;
Now I need to also do cumulative count as below:
I have found some SQL to count running total, but not case like this one. Could you provide me some advice in this case, please?
Cumulative Sum in SQL Server : In SQL server also you can calculate cumulative sum by using sum function. We can use same table as sample table. select dept_no Department_no, count(empno) Employee_Per_Dept, sum(count(*)) over (order by deptno) Cumulative_Total from [DBO].
In SQL, a running total is the cumulative sum of the previous numbers in a column.
COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.
Cumulative sums, or running totals, are used to display the total sum of data as it grows with time (or any other series or progression). This lets you view the total contribution so far of a given measure against time.
Here's a way to do it with a CTE instead of a cursor:
WITH Base AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [Count] DESC) RowNum,
[Dept],
[Count]
FROM SR
)
SELECT SR.Dept, SR.Count, SUM(SR2.[Count]) Total
FROM Base SR
INNER JOIN Base SR2
ON SR2.RowNum <= SR.RowNum
GROUP BY SR.Dept, SR.Count
ORDER BY SR.[Count] DESC
Note that this is ordering by descending Count
like your sample result does. If there's some other column that's not shown that should be used for ordering just replace Count
in each of the ORDER BY
clauses.
SQL Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With