Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to sum Column value

Author  Topic 

Tangled
Starting Member

1 Post

Posted - 2011-03-30 : 20:54:33
Hello,

I have two tables , Namely Tab1 and Tab2

Tab1 has following column and Values

Col1 --- Col2 --- Col3 --- col4

AA --- BB --- CC --- DD

Tab2 has column and Values

Col1 ---- Col2

AA ---- 40
BB ---- 50
CC ---- 60
DD ---- 70

I am expecting results in following way

Col1 -- Col2 -- Col3 -- Col4 -- Col5 -- Col6
AA -- BB -- CC -- DD -- SUM(AA:DD) SUM (DD:AA)

Is there a easy way to accomplish this using SELECT statements ??

Appreciated ...!

Thanks

raghuveer125
Constraint Violating Yak Guru

285 Posts

Posted - 2011-03-31 : 01:52:32
Ok here is one way to do
create table t (val int,val1 int,val2 int,val3 int,val4 int)
insert into t
select 10,150,120,200,300 union all
select 20,205,120,200,300 union all
select 30,300,120,200,300

declare @clumn nvarchar(max),@q nvarchar(max)
select @clumn= COALESCE(@clumn+ '+'+Name+'',''+Name+'') from sys.columns where object_id=2059154381
set @q='select '+@clumn+' From t'
exec (@q)


see when you create table it create object_id.In my database the table object_id is 2059154381
In your case it may be change you need to find and change this object_id

/* This is working on sql sever 2005*/

Raghu' S
Go to Top of Page
   

- Advertisement -