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 take average and append to database

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2007-01-15 : 11:06:46
Ivan writes "Hello,
I am very new to SQL so this may be super easy, or rediculously complex... not sure.

I have a database with a bunch of customers and their total purchase (as well as other junk)on each instance. I want to append a new column to the database that is equal to the average purchase each person makes.

In other words the current db looks like:

(user ID), (purchase amount), (date)

1, 2, 1/1/01
1, 6, 1/3/01
1, 10, 1/10/01
2, 52, 1/4/01
2, 32, 1/7/01
3, 12, 1/1/01

user 1 made 3 purchases of 2, 6, and 10 dollars. That is 18 dollars over 3 purchases so 6 dollars on average.

The new db would be:

(user ID), (purchase amount), (date), (average purchase)

1, 2, 1/1/01, 6
1, 6, 1/3/01, 6
1, 10, 1/10/01, 6
2, 52, 1/4/01, 42
2, 32, 1/7/01, 42
3, 12, 1/1/01, 12

how do I get SQL to calculate the average purchase for each customer and insert that value into every instance of the customer's average purchase field?

the database is static, in that no more data will be added, so a one time aggregation dump is what I need.

Thanks for the help,
Ivan"

Vijaykumar_Patil
Posting Yak Master

121 Posts

Posted - 2007-01-15 : 11:38:27
INSERT INTO NewdB
([User ID],[purchase amount],[date])
SELECT [User ID],[purchase amount],[date]) FROM olDB

SELECT [user ID] ,(sum(purchaseamount))/count(purchaseamount)as [average purchase] INTO temp_average FROM olDB
GROUP BY [user ID]

UPDATE Newdb
SET
[average purchase] = b.[average purchase]
FROM newdb a
JOIN temp_average b
ON a.[user ID]= b.[user ID]

DROP TABLE temp_average


This should give you the desired results.



Necessity is the mother of all inventions!
Go to Top of Page
   

- Advertisement -