Solved

MYSQL PHP: How do I calculate percentage change from mysql table?

Posted on 2008-06-11
14
2,183 Views
Last Modified: 2013-12-13
MYSQL PHP

Hello,

I have a MySQL table with 2 fields:

[ Date ] [ Value ]
2008-06-11 2200
...
2008-05-11 2000


I would like to calculate the percentage increase or decrease as at the last date (e.g. 2007-12-31), when compared to 1 month ago.

So in the example, I want to calculate (2200-2000) / 2000

How do I write this in a mysql query in a PHP script?


Thanks.
0
Comment
Question by:gingera
  • 8
  • 6
14 Comments
 
LVL 9

Accepted Solution

by:
Rob Siklos earned 500 total points
ID: 21762713
Assuming there is only one record for each day, you should be able to do something like this:
$date = "2008-06-11";
 

$sql = "SELECT (t1.value - t2.value)/t2.value AS result

FROM table t1

LEFT JOIN table t2

ON t2.`date` = DATE_SUB(t1.`date`, INTERVAL 1 MONTH)

WHERE t1.`date` = '$date'";

Open in new window

0
 

Author Comment

by:gingera
ID: 21763029
Thanks Rob. Hmmm... I yielded no result with your query.

i.e. when I

echo "$result";

nothing appeared.
0
 
LVL 9

Expert Comment

by:Rob Siklos
ID: 21763071
I just tested it and it worked for me.  Can you post the PHP code you're using to execute the query and print the result?
0
 
LVL 9

Expert Comment

by:Rob Siklos
ID: 21763082
Oh, also, for robustness I would change the LEFT JOIN to INNER JOIN
0
 

Author Comment

by:gingera
ID: 21763169
OK this is the code I tried

Table name: rice

Table fields: date, close
<?php
 

$connection = mysql_connect('localhost', 'username', 'password');

$db = mysql_select_db('prices', $connection);

$query_percentage_change = 	"SELECT ((t1.`close` - t2.`close`)/t2.`close`) AS percentage_change

					FROM `rice` t1

					INNER JOIN `rice` t2

					ON t2.`date` = DATE_SUB(t1.`date`, INTERVAL 1 MONTH)

					WHERE t1.`date` = (SELECT MAX(`date`) FROM `rice`) ";

	$result_percentage_change = mysql_query($query_percentage_change);

	while ( $row = mysql_fetch_array($result_percentage_change) )

	{

			extract($row);

			echo "$percentage_change";

	}

?>

Open in new window

0
 

Author Comment

by:gingera
ID: 21763187
I got error message

PHP Warning:  mysql_fetch_array(): supplied argument is not a valid MySQL result resource
0
 
LVL 9

Expert Comment

by:Rob Siklos
ID: 21763201
before "extract($row);" can you add "print_r($row);" and see what gets printed?
0
Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

 

Author Comment

by:gingera
ID: 21763260
OK, did that. Nothing displayed.
0
 
LVL 9

Expert Comment

by:Rob Siklos
ID: 21763263
Seems like there's something wrong with the result of the call to mysql_query().

After that line, try adding this:

if (!$result_percentage_change) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    die($message);
}
0
 

Author Comment

by:gingera
ID: 21763294
OK I have a possible explanation.

Maybe there is no data for the date exactly 1 month before. For example, a weekend?

If that is the case, how can we find the next closes date to 1 month (if possible)?
0
 

Author Comment

by:gingera
ID: 21763340
OK I changed "interval 1 month" to "interval 2 month" and a result is displayed.

So the problem is as I have described above.

How do I solve this problem (no data for exactly 1 month ago)?
0
 
LVL 9

Expert Comment

by:Rob Siklos
ID: 21763355
Ok, that is a different problem for sure.

At first thought, I would say that you need a routine in PHP to select the date you want to compare to.
0
 

Author Comment

by:gingera
ID: 21763376
OK I am closing this question and allocating the points to you Rob. Thanks very much for your help.

I will start another question. THANKS!
0
 

Author Closing Comment

by:gingera
ID: 31466259
Thanks for your patience for this newbie.
0

Featured Post

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now