I’m using PHP and MySQL and have the following table structure:
date | name | value
2012-11-20 10:30:03 visits 503
2012-10-23 09:30:03 pageviews 567
2012-09-23 09:30:03 pageviews 345
2012-10-20 11:30:03 visits 874
I need to run a MySQL query that compares the two most recent records for each name / value pair and returns if the name / value pair has gone down or up in value.
For example, using the sample data above, the query would return that pageviews has gone up while visits has gone down.
If you wanted to do the compare fully in
MySQL, you can do it in 2 steps.See the SQLFiddle here – http://sqlfiddle.com/#!2/80677/9/0. note – SQLFIDDLE does not allow
CREATE TEMPORARY TABLE, so I had to modify it toCREATE TABLEFirst, you will need to create a temporary table, that will contain just the last 2 rows of each
namegroup-Then you will compare each of those 2 rows to determine if it has gone up or down-
If your table structure is the same as you posted –
(date,name,value)– then the only change you would need to make is where it saystable_namein theCREATE TEMPORARY TABLEquery.In PHP you can then echo –