| Author |
Topic |
|
frank.svs
Constraint Violating Yak Guru
368 Posts |
Posted - 2009-06-16 : 23:11:54
|
| Hi Friends,I need a report query where in i need to display the running totals w.r.t departments.Please help me out!Here is the source data along with my query.CREATE TABLE EMPP(EMPNO INT, ENAME VARCHAR(20),SAL INT,DEPTNO INT)INSERT INTO EMPP SELECT 7840,'MANISH',2000,10UNION ALLSELECT 7399,'GAYLE',3000,10UNION ALLSELECT 5389,'SIDHU',7000,20UNION ALLSELECT 7690,'ARVIND',3000,20UNION ALLSELECT 9390,'AJAY',8000,10UNION ALLSELECT 9373,'KALYAN',2000,20UNION ALLSELECT 6399,'RAMA',5000,30UNION ALLSELECT 8390,'MAHER',6000,30UNION ALLSELECT 9300,'RAVI',3000,30with cte as (select row_number() over(order by deptno) as "seq_no" ,row_number() over(partition by deptno order by deptno) as "seq_no_deptno" ,empno ,ename ,deptno ,sal from empp a ) select a.seq_no ,a.seq_no_deptno ,a.empno ,a.ename ,a.deptno ,a.sal ,(select sum(b.sal) from cte b where b.seq_no <=a.seq_no) as "RunningTotal"from cte as a -- output /* sal runningTotal1 1 7840 MANISH 10 2000 20002 2 7399 GAYLE 10 3000 50003 3 9390 AJAY 10 8000 130004 1 9373 KALYAN 20 2000 150005 2 5389 SIDHU 20 7000 220006 3 7690 ARVIND 20 3000 250007 1 6399 RAMA 30 5000 300008 2 8390 MAHER 30 6000 360009 3 9300 RAVI 30 3000 39000*/-- The above is right, but my other requirement is , can i get running the w.r.t. departments-- Typically, my output should look like below one : i need add a new column "RunningTotalWRTDept" to the output/*seq_no seq_no_deptno empno ename deptno sal runningTotal RunningTotalWRTDept1 1 7840 MANISH 10 2000 2000 20002 2 7399 GAYLE 10 3000 5000 50003 3 9390 AJAY 10 8000 13000 130004 1 9373 KALYAN 20 2000 15000 2000 -- this is reseted for deptno=20 observe!!!5 2 5389 SIDHU 20 7000 22000 90006 3 7690 ARVIND 20 3000 25000 120007 1 6399 RAMA 30 5000 30000 5000 -- this is again resetted for dept=308 2 8390 MAHER 30 6000 36000 110009 3 9300 RAVI 30 3000 39000 14000*/Thanks in advance. |
|
|
waterduck
Aged Yak Warrior
982 Posts |
Posted - 2009-06-16 : 23:29:45
|
| [code]with cte as (Select row_number() over(order by deptno) as "seq_no" ,row_number() over(partition by deptno order by deptno) as "seq_no_deptno" ,empno ,ename ,deptno ,sal from empp a) select a.seq_no ,a.seq_no_deptno ,a.empno ,a.ename ,a.deptno ,a.sal ,(select sum(b.sal) from cte b where b.seq_no <=a.seq_no) as "RunningTotal" ,(select sum(b.sal) from cte b where b.seq_no <=a.seq_no and b.deptno=a.deptno) as "RunningTotalWRTDept"from cte as a [/code] |
 |
|
|
frank.svs
Constraint Violating Yak Guru
368 Posts |
Posted - 2009-06-17 : 02:23:26
|
| Thank You! |
 |
|
|
|
|
|