mysql 查询按组和总计数获取计数

shi*_*hin 2 mysql sql

我有一个表“table1”,如下所示:

col1
----
1      
1
2
2
2
3
3
Run Code Online (Sandbox Code Playgroud)

我想从这个表中按组计数和总计数如下:

col1    group_count   total_count
-------------------------------------
1       2             7
2       3             7
3       2             7
Run Code Online (Sandbox Code Playgroud)

我试过如下:

SELECT col1, group_count, total_count FROM 
(SELECT col1, COUNT(col1) AS group_count FROM table1 GROUP BY col1) Temp1, 
(SELECT COUNT(col1) AS total_count FROM table1) Temp2
Run Code Online (Sandbox Code Playgroud)

如何以优化的方式做到这一点

the*_*mix 5

优化的方法是首先计算计数,然后简单地将变量放入 select 语句中:

set @rowCount = (select count(col1) from table1);
select col1, count(col1), @rowCount from table1 group by col1;
Run Code Online (Sandbox Code Playgroud)

查看结果

@Meherzad 给出的方法将多次计算行数。但是,如果您想在单个查询中执行此操作,则可以使用:

select col1, count(col1), (select count(col1) from table1) rowCount from table1 group by col1;