Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Tough SQL query... 1

Status
Not open for further replies.

Jen53403

Programmer
Jul 17, 2006
22
I have a database of people and their money contributions. I have 6 columns to keep track of individual contributions, and one column called TotalContribution. I want to write a query that would set TotalContribution equal to the sum of the 6 contribution amounts for each person in the table. How can I write a query to do that? I'm writing SQL for Access. Thanks!!
 
updateb tablename
set TotalContribution = nz(colum1,0)+nz(colum2,0)+nz(colum3,0)+nz(colum4,0)+nz(colum5,0)+nz(colum5,0)
 
sorry! denis your right

on the other hand perhaps jen is writeing sql for access

jen53403 said:
I'm writing SQL for Access.

So. jen if this is for access the nz is right ,but this is a Sql fourm if this is for SQL Server then use ISNULL or COALESCE
 
Of course, if it's Access, the question belongs in the Access forum, not the SQL server forum.
 
Sorry ESquared, I didn't realize there was a difference. I thought this forum was for anything coded in SQL.
 
Jen53403 said:
I have 6 columns to keep track of individual contributions, and one column called TotalContribution.
The thing that makes this a "tough" SQL query is the unnormalized nature of the database. The Individuals and the Contributions should be in separate tables. What will you do when someone makes a seventh contribution?

The wrong answer is "add another column". Because now you will have to update everything (such as your TotalContribution above) that assumes there are only 6 columns.

Far better and more flexible to be able to have an SQL statment like:

SELECT IndividualID, Sum(Contribution) AS TotalContribution FROM Contributions GROUP BY IndividualID

See, now it doesn't matter if someone made 1, 2, 8, or 50 contributions, you will always get the correct sum, and you never have to change your database schema because you need to add more data.

 
Thanks Joe for taking the time to give the answer we all knew but didn't feel like expending the effort to provide.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top