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

我有一个SQLselect查询有一个组。 我想统计所有logging后的logging。 有没有办法从这个直接从SQL? 例如,有一个表与用户我想select不同的城镇和用户总数

select town, count(*) from user group by town 

我想要在所有行中都有一个城镇,而另一个城市的行中有用户。

总共有3个镇和58个用户的例子是:

 Town Count Copenhagen 58 NewYork 58 Athens 58 

这将做你想要的(城镇名单,每个用户的数量):

 select town, count(town) from user group by town 

使用GROUP BY时,您可以使用大多数聚合函数 。

更新 (改变问题和评论之后)

您可以为用户数量声明一个variables,并将其设置为用户数量,然后使用该数量进行select。

 DECLARE @numOfUsers INT SET @numOfUsers = SELECT COUNT(*) FROM user SELECT DISTINCT town, @numOfUsers FROM user 

您可以使用COUNT(DISTINCT ...)

 SELECT COUNT(DISTINCT town) FROM user 

另一种方式是:

 /* 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 

使用Oracle,您可以使用分析function:

 select town, count(town), sum(count(town)) over () total_count from user group by town 

您的其他选项是使用子查询:

 select town, count(town), (select count(town) from user) as total_count from user group by town 

如果你想通过计数(听起来很简单,但我不能find一堆答案),你可以这样做:

  SELECT town, count(town) as total FROM user GROUP BY town ORDER BY total DESC 

你可以在COUNT里面使用DISTINCT,就像milkovsky说的那样

在我的情况下:

 select COUNT(distinct user_id) from answers_votes where answer_id in (694,695); 

这将拉回被认为相同的user_id作为一个计数的答案票数

我知道这是一个旧的职位,在SQL Server中:

 select isnull(town,'TOTAL') Town, count(*) cnt from user group by town WITH ROLLUP Town cnt Copenhagen 58 NewYork 58 Athens 58 TOTAL 174 

如果你想select镇和总用户数,你可以使用下面的查询:

 SELECT Town, (SELECT Count(*) FROM User) `Count` FROM user GROUP BY Town; 

试试下面的代码:

 select ccode, count(empno) from company_details group by ccode;