sql sum,group by 分组求和后在求总和,with rollup,with cube的区别

您所在的位置:网站首页 怎么样分组 sql sum,group by 分组求和后在求总和,with rollup,with cube的区别

sql sum,group by 分组求和后在求总和,with rollup,with cube的区别

2024-06-08 06:35| 来源: 网络整理| 查看: 265

有表数据如下:

create table tt ( name varchar(10), num decimal(18,2), ph int ) insert into tt(name,num,ph) values ('test1',10,1) insert into tt(name,num,ph) values ('test1',30,1) insert into tt(name,num,ph) values ('test1',50.5,3) insert into tt(name,num,ph) values ('test2',60,2) insert into tt(name,num,ph) values ('test2',2.65,2) insert into tt(name,num,ph) values ('test2',66.8,3) select * from tt

在这里插入图片描述

想要根据name,ph字段分组 求 num 总和 使用聚合函数sum+group by

select name,ph,sum(num) as num from tt group by name,ph order by name

得到结果 在这里插入图片描述 怎样得到相同name的 总 num 呢? 1,使用 WITH ROLLUP,此函数是对聚合函数进行求和,注意 with rollup是对 group by 后的第一个字段,进行分组求和

select name,ph,sum(num) as num from tt group by name,ph WITH rollup

结果如图:在这里插入图片描述

2,使用 with cube

select name,ph,sum(num) as num from tt group by name,ph with cube

该函数是对group by 后的所有字段进行 分组求和,顺序为group by后的字段从右到左,分组求和 在这里插入图片描述 童鞋们,这个截图和解释 应该很详细了,想必大家都可以看的懂吧,有不懂的可以私信dd



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3