我有一个SQL SELECT查询,也使用GROUP BY, 我想统计GROUP BY子句过滤结果集后的所有记录。

有什么方法可以直接用SQL做到这一点吗?例如,如果我有用户表,想要选择不同的城镇和用户总数:

SELECT `town`, COUNT(*)
FROM `user`
GROUP BY  `town`;

我想有一个列的所有城镇和另一个与用户的数量在所有行。

一个有3个镇和58个用户的结果的例子是:

Town Count
Copenhagen 58
New York 58
Athens 58

当前回答

你可以使用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

你可以使用COUNT(DISTINCT…):

SELECT COUNT(DISTINCT town) 
FROM user

试试下面的代码:

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

你可以像milkovsky说的那样在COUNT中使用DISTINCT

在我的例子中:

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

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

在Oracle中,你可以使用分析函数:

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