如何使用遞迴實現資料的累加

來源:互聯網
上載者:User
--關於遞迴累計求和-->>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*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.