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

编程入门 行业动态 更新时间:2024-10-24 23:17:38
本文介绍了mysql 查询按组和总计数获取计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a table 'table1' as follows:

col1 ---- 1 1 2 2 2 3 3

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

I want to get count by group and total count from this table as follows:

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

优化方法

推荐答案

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

the optimized way is to first calculate the count and then simply put the variable in your select statement:

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

查看结果

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

The approach given by @Meherzad will calculate the row count many times. But if you want to do this in a single query u can use:

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

更多推荐

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

本文发布于:2023-10-31 07:46:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:mysql

发布评论

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

>www.elefans.com

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