oracle某一字段分组求和,关于对某列进行分组求和的有关问题

这篇博客展示了如何使用SQL进行数据分组统计,并通过UNION ALL合并两个查询结果,最后按照ID和统计值排序。创建了一个名为mytest的测试表,插入数据后,分别以ID和ID、pro_name为条件进行分组统计cast值,最终得到合并后的查询结果并排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SQL code--创建测试表mytest

create table mytest(

id number,

pro_name varchar(20),

cast number

)

--插入数据

insert into mytest values(1,'lass',100)

insert into mytest values(1,'tass',200)

insert into mytest values(1,'sass',100)

insert into mytest values(1,'mass',200)

insert into mytest values(1,'yass',100)

insert into mytest values(1,'uass',200)

--分两步查询

1、以id、pro_name分组统计

select id,pro_name,sum(cast)sum_cast from mytest group by id,pro_name order by id

结果如下:

2、以id分组统计

select id,''pro_name,sum(cast)sum_cast from mytest group by id order by id

结果如下:

[img=http://b151.photo.store.qq.com/psb?/b1320946-81af-4671-9124-ef998a845dfb/p0Zmwitb3NTgDt62ic6X15nw4n6SUj.ArBY5DJB16hs!/b/YT59C1qMRQAAYvgGDVqGSgAA][/img]

--合并查询:

select a.* from(select id,pro_name,sum(cast)sum_cast from mytest group by id,pro_name)a

union all

select b.* from(select id,''pro_name,sum(cast)sum_cast from mytest group by id)b

--按id排序

select * from(

select a.* from(select id,pro_name,sum(cast)sum_cast from mytest group by id,pro_name)a

union all

select b.* from(select id,''pro_name,sum(cast)sum_cast from mytest group by id)b

) order by id,sum_cast

查询结果如下:

[img=http://b203.photo.store.qq.com/psb?/b1320946-81af-4671-9124-ef998a845dfb/D91LDiDJ9cDtM**O6XF3WPDwDUVHbB8kRPtniiq3gl8!/b/YX0hEHkesQAAYn0hEHkdsQAA][/img]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值