Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

The Database Forum


You are currently viewing our The Database Forum as a guest. Please register to participate.
Login



Reply
Old 01-02-2010, 04:27 PM MySQL summing
Junior Talker

Posts: 1
Name: Miha
Trades: 0
Hello guys!

I have one problem.
On MySQL database I have table with name 'all_visitors' and there I have two column...
id Visitors
1 5690
2 5434
3 234
... ...
x 45455
y 45858

How can I sum last five Visitors?

I use...
PHP Code:
$sql "SELECT SUM(Visitors) FROM all_visitors ORDER BY id DESC LIMIT 5";

$result_query mysql_query($sql);
$result mysql_fetch_array($result_query);
$sum_five_visitors $result[0];

echo 
''.$sum_five_visitors.''
...but this function sum all Visitors.

Thank you 4 answer ... and sorry 4 my bad english.
b3wk is offline
Reply With Quote
View Public Profile
 
 
Register now for full access!
Old 01-06-2010, 03:56 PM Re: MySQL summing
Junior Talker

Posts: 2
Trades: 0
Code:
SELECT SUM(visitors) FROM all_visitors WHERE id >= (SELECT id from all_visitors ORDER BY id DESC limit 5,1)
As far as I know, you need a WHERE clause to narrow down the results for the SUM to work. The subquery grabs the fifth-to-last ID in the table, and the main query only show results greater than or equal to that ID.

A GROUP BY clause would probably narrow it down for you too, but I couldn't think of a good way to fit that in in this instance.

You could also just grab the last 5 entries without using SUM, and use a PHP loop to add them up.

Last edited by Llama Herder; 01-06-2010 at 04:03 PM..
Llama Herder is offline
Reply With Quote
View Public Profile
 
Reply     « Reply to MySQL summing
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.09506 seconds with 12 queries