我有一个表'table1'如下:
col1
----
1
1
2
2
2
3
3
我希望按照以下方式按组和总计数计算:
col1 group_count total_count
-------------------------------------
1 2 7
2 3 7
3 2 7
我尝试如下:
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
如何以优化方式完成
答案 0 :(得分:4)
优化的方法是首先计算计数,然后简单地将变量放在select语句中:
set @rowCount = (select count(col1) from table1);
select col1, count(col1), @rowCount from table1 group by col1;
@Meherzad给出的方法将多次计算行数。但是如果你想在一个查询中执行此操作,你可以使用:
select col1, count(col1), (select count(col1) from table1) rowCount
from table1 group by col1;
答案 1 :(得分:1)
尝试此查询
select col1, count(*), tot
from tbl t1, (select count(*) as tot from tbl) t2
group by col1