如何在同一个select语句中使用count和group by

编程入门 行业动态 更新时间:2024-10-20 00:24:29
本文介绍了如何在同一个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

本文发布于:2023-11-22 06:42:15,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   在同一个   group   select   count

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!