对表中的记录分组,并求每组所占百分比

HDM1991 2015-01-14 10:46:51
有人做过对一个表中的记录分组,并求每组所占百分比的需求吗。

这个我的SQL语句,该SQL语句包含一个子查询,子查询对dns_messages表中满足过滤条件的记录通过hostname进行分组,计算每组的个数,并进行排序,然后主体部分把从子查询部分获取的结果(即每个分组的名字hostname和每个分组的个数nums)作为一个表tt,从中获取在分组的个数nums大于1000的记录中,从索引2开始起的10个记录

select * from (select hostname, count(*) as nums from dns_messages where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" group by hostname order by nums desc, hostname desc) as tt where nums >= 1000 limit 2,10


现在的需求就是计算上述sql语句获取的10个记录中,每个分组的个数所占的百分比nums/sum。这个百分比的基数sum可以用如下的SQL语句表示,即上述SQL语句中的子查询部分获取的所有的分组的nums的和
select  sum(nums) from (select hostname, count(*) as nums from dns_messages where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" group by hostname order by nums desc, hostname desc) as tt


我现在的疑问就是怎样在一条SQL语句中即获取分组,分组的个数,又获取百分比,难道要这样写
select hostname, nums, nums/sums, sums from (select hostname, count(*) as nums from dns_messages where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" group by hostname order by nums desc, hostname desc) as tt, (select count(*) as sums from dns_messages where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00")  as dd where nums >= 1000 limit 2,10

有其他方法吗?
...全文
311 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
HDM1991 2015-01-14
  • 打赏
  • 举报
回复
引用 1 楼 ACMAIN_CHM 的回复:
select hostname, count(*) as nums ,count(*) /sums,sums from dns_messages , (select count(*) as sums from dns_messages where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" ) as dd where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" group by hostname order by nums desc, hostname desc
谢谢版主,看来如果想要在一条语句中完成,一个用于计算基数的子查询是少不了的了
ACMAIN_CHM 2015-01-14
  • 打赏
  • 举报
回复
select hostname, count(*) as nums ,count(*) /sums,sums from dns_messages , (select count(*) as sums from dns_messages where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" ) as dd where capture_date >= "1991-01-01 00:00:00" and capture_date <= "2020-01-01 00:00:00" group by hostname order by nums desc, hostname desc

56,685

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧