How to use count and group by at the same select statement

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:

(COUNT, MAX, COUNT DISTINCT etc.)

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

Leave a Comment