--關於遞迴累計求和-->>TravyLee產生測試資料if OBJECT_ID('test')is not nulldrop table testgocreate table test(id int identity(1,1),deptid char(3),empid char(4),salary int)goinsert test(deptid,empid,salary)select '101','1001',3500 union allselect '101','1002',2200 union allselect '102','1003',1900 union allselect '102','1004',5600 union allselect '102','1005',8000 union allselect '101','1006',2400 union allselect '101','1007',2300 union allselect '103','1008',3200 union allselect '103','1009',7800 union allselect '104','1010',4500 union allselect '101','1011',6500 union allselect '104','1012',3500 union allselect '104','1013',1900 union allselect '103','1014',2700 union allselect '102','1015',3100 union allselect '104','1016',2600 go--problem 1:求出所有員工的工資的累計(從工資的最高到最低累計);with tas(select px=ROW_NUMBER()over(order by salary desc),deptid,empid,salaryfrom test),m as(select px,deptid,empid,salary,salary as total from t where px=1union allselect a.px,a.deptid,a.empid,a.salary,b.total+a.salaryfrom t ajoin m b on a.px=b.px+1 )select deptid,empid,salary,total from mgo/*deptid empid salary total------------------------------11021005800080002103100978001580031011011650022300410210045600279005104101045003240061011001350035900710410123500394008103100832004260091021015310045700101031014270048400111041016260051000121011006240053400131011007230055700141011002220057900151021003190059800161041013190061700*/--problem 2:分部門統計,並求出各部門在總工資中所佔的百分比;with tas(select px=ROW_NUMBER()over(partition by deptid order by salary desc),deptid,empid,salaryfrom test),m as(select px,deptid,empid,salary,salary as total from t where px=1union allselect a.px,a.deptid,a.empid,a.salary,b.total+a.salaryfrom t ajoin m b on a.px=b.px+1 and a.deptid=b.deptid)select deptid,empid,salary,total from m order by deptid,px/*deptid empid salary total------------------------------10110116500650010110013500100001011006240012400101100723001470010110022200169001021005800080001021004560013600102101531001670010210031900186001031009780078001031008320011000103101427001370010410104500450010410123500800010410162600106001041013190012500*/