Home Forums Gamescan Chat42 About
* Login   * Register * FAQ    * Search
It is currently Fri 05-17-2024 4:24PM

All times are UTC - 6 hours




Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: SQL help
PostPosted: Sun 10-29-2006 10:15PM 
Offline
Brigadier General

Joined: Tue 01-22-2002 12:35PM
Posts: 1057
Location: Shawnee Mission, KS

Source: Off Campus
Suppose I have a table that shows trips to Wal-Mart. It keeps track of who went, when he/she went, and how much he/she spent:
Code:
name   date         amount
-----------------------------
Alice    1/1/06      $45.34
Bob     1/2/06      $2.72
Charles 1/2/06     $3.14
Alice    1/5/06      $42.42
Charles 1/10/06   $105.32
Bob     1/15/06    $88.00


Suppose that I then want to make a view (or a query, whatever) with 2 columns: the name of each person and the average amount that he/she spent over all of his/her trips. For this data set it would look like:

Alice 43.88
Bob 45.36
Charles 54.23

When I tried a query like
Code:
SELECT name, ( (SELECT amount FROM trips) / (SELECT CAST(COUNT(name) AS FLOAT) ) ) AS average FROM trips USING name GROUP BY name;

it produces the average amount spent per trip for every entry in the table, like so:

Code:
name   average
-------------------
Alice        $47.82
Bob         $47.82
Charles    $47.82


How can I get it to do the math for each person individually? You can assume the name column is foreign-keyed to a "people" table if that's necessary.

EDIT: Well, I figured out at least one way to do it:
Code:
SELECT DISTINCT people.name,
( (SELECT ( SUM (trips.amount) ) WHERE (people.name = trips.name)) / (SELECT ( CAST (COUNT(trips.name) AS FLOAT) ) ) AS average
FROM people INNER JOIN trips ON (people.name = trips.name);


Top
 Profile E-mail  
    
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 7 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
cron
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group