Monday, October 19, 2015

Row and Column wise sum in a table using Sqlserver



CREATE TABLE [dbo].[tbl_Sample](
[ColumnA] [int] NOT NULL,
[ColumnB] [int] NOT NULL,
[ColumnC] [int] NULL
) ON [PRIMARY]

GO

SELECT  [ColumnA]
      ,[ColumnB]
      ,[ColumnC]
  FROM [SampleTest].[dbo].[tbl_Sample]

UPDATE tbl_Sample
SET ColumnC = (ColumnA+ColumnB)
FROM (
      SELECT ROW_NUMBER() OVER (ORDER BY [COLUMNA]) AS tbl_Sample
      FROM tbl_Sample
      ) x

INSERT INTO tbl_Sample(ColumnA,ColumnB,ColumnC)
SELECT SUM(ColumnA),SUM(ColumnB),SUM(ColumnC)
FROM tbl_Sample

SELECT  [ColumnA]
      ,[ColumnB]
      ,[ColumnC]
  FROM [SampleTest].[dbo].[tbl_Sample]

No comments:

Post a Comment