SQL使用递归实现数据的累加

本文通过SQL示例展示了如何利用递归和CTE(通用表表达式)来解决两个问题:1) 计算所有员工按工资从高到低的累计总工资;2) 分部门统计工资并计算各部门在总工资中的百分比。通过对test表的数据操作,详细解释了递归CTE的使用方法。

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

--关于递归累计求和 
if OBJECT_ID('test')is not null  
drop table test  
go  
create table test(  
id int identity(1,1),  
deptid char(3),  
empid char(4),  
salary int  
)  
go  
insert test(deptid,empid,salary)  
select '101','1001',3500 union all  
select '101','1002',2200 union all  
select '102','1003',1900 union all  
select '102','1004',5600 union all  
select '102','1005',8000 union all  
select '101','1006',2400 union all  
select '101','1007',2300 union all  
select '103','1008',3200 union all  
select '103','1009',7800 union all  
select '104','1010',4500 union all  
select '101','1011',6500 union all  
select '104','1012',3500 union all  
select '104','1013',1900 union all  
select '103','1014',2700 union all  
select '102','1015',3100 union all  
select '104','1016',2600   
go  
--problem 1:求出所有员工的工资的累计(从工资的最高到最低累计)  
;with t  
as(  
select   
px=ROW_NUMBER()over(order by salary desc),  
deptid,empid,salary  
from test  
),  
m as(  
select px,deptid
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值