Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Cumulative Count

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:

enter image description here

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?

like image 780
DNac Avatar asked Oct 14 '13 13:10

DNac


People also ask

How do you do a cumulative count in SQL?

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].

What is cumulative sum in SQL?

In SQL, a running total is the cumulative sum of the previous numbers in a column.

What does count (*) do in SQL?

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.

What is meant by cumulative sum?

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.


1 Answers

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

like image 146
D Stanley Avatar answered Sep 22 '22 12:09

D Stanley