我有一个具有group by的sql select查询。 我想计算group by语句后的所有记录。 有直接从sql的方法吗? 例如,拥有一个包含用户的表格我想选择不同的城镇和总用户数量
select town,count(*)from user group by town
有三个城镇和58个用户的结果示例,其中包括所有城市的列和所有行的用户数。总计是:
城市数哥本哈根58 纽约58 雅典58解决方案
这将做你想要的(城镇列表,
select town,count(town) from user group by town您可以使用大多数 GROUP BY 时,聚合函数。
更新(更改问题和意见后)
您可以为用户数量声明一个变量,
DECLARE @numOfUsers INT SET @numOfUsers = SELECT COUNT(*)FROM用户 选择DISTINCT镇,@numOfUsers 从用户
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 townI 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解决方案
This will do what you want (list of towns, with the number of users in each):
select town, count(town) from user group by townYou 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
更多推荐
如何在同一个select语句中使用count和group by
发布评论