简体   繁体   中英

How to compare two most recent records foreach column name pair

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 to CREATE TABLE

First, you will need to create a temporary table, that will contain just the last 2 rows of each name group-

CREATE TEMPORARY TABLE tmptable
   SELECT * FROM
        (SELECT IF(@prev != sq.name, @rownum:=1, @rownum:=@rownum + 1) AS rownumber, @prev:=sq.name, sq.* FROM
       (SELECT * FROM table_name , (SELECT @rownum:=0, @prev:=0) r ORDER BY name, date DESC ) sq
   ) q WHERE q.rownumber <=2;

Then you will compare each of those 2 rows to determine if it has gone up or down-

SELECT a.name,
       IF(a.value > b.value, 'up', 'down') action
FROM tmptable a
JOIN tmptable b 
ON a.name = b.name AND a.date > b.date ORDER BY a.date DESC;

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 says table_name in the CREATE TEMPORARY TABLE query.

In PHP you can then echo -

while($row = ...fetch_array($query)){
  echo $row['name'] ." -> ".$row['action']."<br />";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM