如何在同一个select语句中使用count和group by [英] How to use count and group by at the same select statement

查看:134
本文介绍了如何在同一个select语句中使用count和group by的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有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 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

解决方案

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

这篇关于如何在同一个select语句中使用count和group by的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆