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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Summating Columns

Author  Topic 

starnold
Yak Posting Veteran

83 Posts

Posted - 2008-06-17 : 07:02:03
I have a database that has several columns of product spend data that I need to add together.

Example:

URN Prod1 Prod2 Prod3 Prod4
1 500 500 500 500
2 750 750 750 750
4 100 400 800 500
5 300 600 500 500
6 200 700 400 500

I would like to add Prod1 & Prod2 totals together and Prod3 & Prod4 totals together to give me 2 unique columns with the total value?

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2008-06-17 : 07:09:09
Why not try to do exactly as you have said?

select
URN,
sum(Prod1+Pro2) as Sum1,
sum(prod3+Prod4) as Sum2
from table
group by URN
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-06-17 : 07:11:14
quote:
Originally posted by RickD

Why not try to do exactly as you have said?

select
URN,
sum(Prod1+Pro2) as Sum1,
sum(prod3+Prod4) as Sum2
from table
group by URN



Is the group by required? the sample data doesnt seem like having multiple records with same URN value.
Go to Top of Page

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2008-06-17 : 07:16:42
No, but you can guarantee it will be..

Actually, yes it is if you want to use sum(), but not if you just take the sum() out. If you can guarantee 1 row for each URN then you can just do:

select
URN,
Prod1+Prod2 as Sum1,
prod3+Prod4 as Sum2
from table


Go to Top of Page

starnold
Yak Posting Veteran

83 Posts

Posted - 2008-06-17 : 07:26:00
thanks I assumed it was as easy as that but wanted clarification. How can I get it to avoid not summing the nulls?
Go to Top of Page

RickD
Slow But Sure Yak Herding Master

3608 Posts

Posted - 2008-06-17 : 07:40:44
put an isnull(<field>,0) around each field.
Go to Top of Page
   

- Advertisement -