views:

192

answers:

2

Hello, I have an sql select query that has a group by. I want to count all the records after the group by statement. Is there a way for this directly from sql? For example, having a table with users I want to select the different towns and the total number of users

select town, count(*) from user
group by town

I want to have a column with all the towns and another with the number of users in all rows.

An example of the result for having 3 towns and 58 users in total is :

Town         Count
Copenhagen   58
NewYork      58
Athens       58
+5  A: 

This will do what you want (list of towns, with the number of users in each):

select town, count(town) 
from user
group by town

You can use most aggregate functions when using GROUP BY.

Update (following change to question and comments)

You can declare a variable for the number of users and set it to the number of users then select with that.

DECLARE @numOfUsers INT
SET @numOfUsers = SELECT COUNT(*) FROM user

SELECT DISTINCT town, @numOfUsers
FROM user
Oded
that's exactly what the OP wrote? nvm, i see your difference, you're counting Town not *....
Leslie
@Leslie - there is no difference between the two queries. They will return the same result set. I just dislike the use of `*`... The OP answered his own question, but did not seem to even test it, I am just validating that it is correct :) http://www.fredosaurus.com/notes-db/select/groupby.html
Oded
COUNT(*) may not equal COUNT(Town). Using * in COUNT is perfectly valid...
gbn
I want the total number of users. Not the users per town..
Stavros
Again not what I hoped for, but it seems that this is the best solution.. ;) Thanks
Stavros
A: 

With Oracle you could use analytic functions:

select town, count(town), sum(count(town)) over () total_count from user
group by town

Your other options is to use a subquery:

select town, count(town), (select count(town) from user) as total_count from user
group by town
Tommi
something like the last one would work, but I wanted to see if there is any other solution..
Stavros
And cannot you use the first (analytic function) option? What database platform are you using?
Tommi
@Stavros: The last one is slow
Michael Buen