How to use count and group by at the same select statement
The other way is:
/* Number of rows in a derived table called d1. */
select count(*) from
(
/* Number of times each town appears in user. */
select town, count(*)
from user
group by town
) d1
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
You can use COUNT(DISTINCT ...)
:
SELECT COUNT(DISTINCT town)
FROM user