文章详情页
mysql - 请问如何统计group by 后的结果
问题描述
比如这条语句可以统计查询总数
SELECT COUNT(`id`) AS `num` FROM `test`;
那如果加了一句group by 之后就不对了
SELECT COUNT(`id`) AS `num` FROM `test` GROUP BY `id`;
请问我想要知道GROUP BY出来有多少行数据,怎么做
问题解答
回答1:统计GROUP BY后的数据行数:
SELECT count(1) FROM ( SELECT * FROM `test` GROUP BY `id`) AS tmp;
统计id相同出现的次数:
SELECT id, count(1) FROM `test` GROUP BY `id`;
统计GROUP BY后的数据总和:
SELECT sum(c) FROM ( SELECT count(1) AS c FROM `test` GROUP BY `id`) AS tmp;
不清楚你想要查什么,但猜测是第一条SQL。
回答2:SELECT id,COUNT(id) AS num FROM test GROUP BY id;
回答3:楼主正解,思路就是先把查找到的结果放在一张“临时表”,然后再统计总数
回答4:楼上正解,题主可参考
相关文章:
排行榜