How to get the running value

 Hi,

I have a requirement in which i need to generate the running value. Please consider the below example.

Empid  Sal Month
1 1000 Jan
1 2000 Jan
1 3000 Jan
1 2000 Feb
1 3000 Feb
1 4000 Feb

I want the output AS

Empid  Sal Month Running Total
1 1000 Jan 1000
1 2000 Jan 3000
1 3000 Jan 6000
1 2000 Feb 2000
1 3000 Feb 5000
1 4000 Feb

9000


Thanks in Advance..!!

July 6th, 2013 11:44pm

Are you using SQL Server 2012?

SELECT *
  SUM(Sal) OVER(PARTITION BY empid
                ORDER BY ordermonth
                ROWS BETWEEN UNBOUNDED PRECEDING
                         AND CURRENT ROW) AS runSal

FROM tbl

Otherwise

with cte
as (
    select row_no = row_number() over( order by empid ), 
    from tbl
   
    )
select t1.*,
       running_amount = coalesce(
                         (  select sum( sal)
                            from cte t2
                            where t2.row_no < t1.row_no
                              and t2.account_id = t1.account_id ), 0 )
                        + sal
from cte t1
order by empid, row_no

Free Windows Admin Tool Kit Click here and download it now
July 7th, 2013 12:13am

Refer the below solution,

DECLARE @temp table(empid int, sal int,month nvarchar(5))
INSERT INTO @temp VALUES(1, 1000, 'Jan' )
INSERT INTO @temp VALUES(1, 2000, 'Jan' )
INSERT INTO @temp VALUES(1, 3000, 'Jan' )
INSERT INTO @temp VALUES(1, 2000, 'Feb' )
INSERT INTO @temp VALUES(1, 3000, 'Feb' )
INSERT INTO @temp VALUES(1, 4000, 'Feb' )
INSERT INTO @temp VALUES(2, 1000, 'Jan' )
INSERT INTO @temp VALUES(2, 2000, 'Jan' )
INSERT INTO @temp VALUES(2, 3000, 'Jan' )
INSERT INTO @temp VALUES(2, 2000, 'Feb' )
INSERT INTO @temp VALUES(2, 3000, 'Feb' )
INSERT INTO @temp VALUES(2, 4000, 'Feb' )
---------------------------------------
DECLARE @finaltemp table(empid int, sal int,month nvarchar(5),runningtotal int)
DECLARE @maxid int,@count int
SELECT @maxid=max(empid) from @temp
SET @count =1
WHILE @count <=@maxid
BEGIN
	;WITH cte as (
	SELECT @count as empid,row_number() over (partition by @count order by @count) as rowid,sal,month from @temp where empid=@count
	)
	INSERT INTO @finaltemp
	SELECT empid,sal,month,runningtotal from (
	SELECT @count as empid,month,rowid,
       sal,
       sal+COALESCE((SELECT SUM(sal) 
                      FROM cte b 
                      WHERE b.rowid < a.rowid),0)
                         AS RunningTotal
	FROM cte a where a.empid = @count
--	ORDER BY rowid
	) x
	SET @count =@count + 1
END
select * from @finaltemp

July 7th, 2013 12:19am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics