Ibrahiem Rafiq
Ibrahiem Rafiq

Reputation: 73

Count within the aggregate SUM()

I have a table with 1000 rows. Columns exist are ID, DBID, TalkTime.

I am doing:

SELECT DBID, SUM(TalkTime)
FROM Incoming_Calls
GROUP BY DBID

This condenses down to approximely 18 rows.

I want to know how I can count the number of records present within each grouping. So for example DBID 105 has a sum of 526 which is made up of 395 records, DBID 104 has a sum of 124 made up using 241 of the records during the grouping.

Any ideas?

Using Microsoft SQL Server 2012.

Upvotes: 1

Views: 1459

Answers (2)

Praveen Mitta
Praveen Mitta

Reputation: 1508

Select DBID, SUM(TalkTime), COUNT(TalkTime) TalkTimeCount 
FROM Incoming_Calls 
GROUP BY DBID

OR, If you want to include null values count then you can you this

Select DBID, SUM(TalkTime), @@ROWCOUNT 
FROM Incoming_Calls 
GROUP BY DBID

Upvotes: 0

John Woo
John Woo

Reputation: 263803

Then use COUNT()

SELECT DBID, 
       COUNT(*) TotalRows, 
       SUM(TalkTime) TotalTalkTime
FROM   Incoming_Calls
GROUP  BY DBID

Upvotes: 4

Related Questions