Hello Sir...
I am working in SQLSERVER and i want to add column value like i have a one table id, salary and i want to output id, add salary like first to second, second to third value?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Bhasker DasPosted Aug 6, 2014, 4:05 AM
Try this -
Generate Sample Table with Records
-----------------------------------------
CREATE TABLE [dbo].[UserTable](
[ID] [int] NOT NULL,
[Name] [varchar](50) NULL,
[Mobile] [varchar](15) NULL,
[Salary] [bigint] NULL,
CONSTRAINT [PK_UserTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[UserTable] ([ID], [Name], [Mobile], [Salary]) VALUES (1, N'Bhasker', N'1236547893', 10000)
INSERT [dbo].[UserTable] ([ID], [Name], [Mobile], [Salary]) VALUES (5, N'Shiv', N'8523698741', 20000)
INSERT [dbo].[UserTable] ([ID], [Name], [Mobile], [Salary]) VALUES (8, N'Davin', N'8546987456', 30000)
INSERT [dbo].[UserTable] ([ID], [Name], [Mobile], [Salary]) VALUES (10, N'Sanjay', N'3214469856', 40000)
-----------------------------------
Now run below script to get your desired output -
SELECT SUM(ISNULL(A.Salary, 0) + ISNULL(B.Salary, 0)) [Cumulative Salary], A.[Computed ID] FROM (SELECT ROW_NUMBER() Over (Order By ID) AS [Computed ID], Salary FROM UserTable) AS A LEFT JOIN (SELECT ROW_NUMBER() Over (Order By ID) AS [Computed ID], Salary FROM UserTable) AS B on A.[Computed ID]=B.[Computed ID]+1 Group By A.[Computed ID], A.Salary, B.Salary
Khan Abrar AhmedPosted Aug 6, 2014, 3:56 AM
DECLARE @table AS TABLE ( id INT, salary MONEY );
DECLARE @tableOutput AS TABLE ( RowID INT, salary MONEY );
DECLARE
@COUNT INT = 0 ,
@maxcount INT= 1
INSERT INTO @table
VALUES
( 1, 1000 ),
( 2, 3000 ),
( 3, 4000 )
SELECT
@count = COUNT(1)
FROM
@table AS t
DECLARE @totalSum MONEY
SELECT
*
FROM
@table AS t
WHILE @COUNT >= @maxcount
BEGIN
IF ( @maxcount = 1 )
BEGIN
SELECT
@totalSum = salary
FROM
@table AS t
WHERE
id = @maxcount
END
ELSE
BEGIN
SELECT
@totalSum = SUM(salary)
FROM
@table AS t2
WHERE
id = @maxcount;
SELECT
@totalSum = @totalSum + salary
FROM
@tableOutput AS t
WHERE
Rowid IN ( @maxcount, @maxcount - 1 )
END
INSERT INTO @tableOutput
( RowID, salary )
VALUES
( @maxcount, -- RowID - int
@totalSum -- salary - money
)
SET @maxcount += 1;
END
SELECT
*
FROM
@tableOutput;
Ankur JainPosted Aug 6, 2014, 1:20 AM
this query works for you...please don't forget to mark it answer if it solve your problem...
Use Demo
Go
Davin MartynPosted Aug 6, 2014, 12:09 AM
Bhasker DasPosted Aug 5, 2014, 2:59 AM