[英]How to compare two most recent records foreach column name pair
I'm using PHP and MySQL and have the following table structure: 我正在使用PHP和MySQL,并具有以下表结构:
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. 我需要运行一个MySQL查询,该查询比较每个名称/值对的两个最新记录,并返回名称/值对的值是否下降或上升。
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. 如果您想在MySQL
完全进行比较,则可以分两步完成。
See the SQLFiddle here - http://sqlfiddle.com/#!2/80677/9/0 . 在此处查看SQLFiddle- http: //sqlfiddle.com/#!2/80677/9/0。 note - SQLFIDDLE does not allow CREATE TEMPORARY TABLE
, so I had to modify it to CREATE TABLE
注意-SQLFIDDLE不允许CREATE TEMPORARY TABLE
,因此我不得不将其修改为CREATE TABLE
First, you will need to create a temporary table, that will contain just the last 2 rows of each name
group- 首先,您需要创建一个临时表,该表仅包含每个name
组的最后2行-
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. 如果您的表结构与您发布的表结构相同(date,name,value)
- (date,name,value)
,那么您唯一需要做的更改就是在CREATE TEMPORARY TABLE
查询中它说table_name
的位置。
In PHP you can then echo - 然后在PHP中可以回显-
while($row = ...fetch_array($query)){
echo $row['name'] ." -> ".$row['action']."<br />";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.