php – 同一个表,按类型分组最大日期,2行差异

我怎样才能做到这一点?我有这张桌子

╔════════╦══════════╦══════════╗
║ item   ║ price    ║ date     ║
╠════════╬══════════╬══════════╣
║ Dollar ║       60 ║ 1.3.2016 ║
║ Dollar ║       50 ║ 2.3.2016 ║
║ Bound  ║      100 ║ 1.3.2016 ║
║ Bound  ║      110 ║ 2.3.2016 ║
║ Euro   ║      600 ║ 1.3.2016 ║
║ Euro   ║      580 ║ 3.3.2016 ║
╚════════╩══════════╩══════════╝

输出应显示每种类型的一个项目,最后一个日期的最终价格为dedepnding,前一行的价格差异如下:

╔════════╦══════════╦════════════════════════╗
║ item   ║ price    ║ date     ║ differnece  ║
╠════════╬══════════╬════════════════════════╣
║ Dollar ║       50 ║ 2.3.2016 ║   -10       ║
║ Bound  ║      110 ║ 2.3.2016 ║    10       ║
║ Euro   ║      580 ║ 3.3.2016 ║   -20       ║
╚════════╩══════════╩════════════════════════╝

我这样做了……

SELECT item,date,price FROM wpdatatable_23 WHERE date IN (SELECT max(date) FROM wpdatatable_23 GROUP BY item LIMIT 0,1) group by item

……它工作正常.我只是不知道如何做差异的事情,任何帮助?

解决方法:

您可以使用相关子查询计算差异:

SELECT item, `date`, price,
       price - (SELECT price
                FROM wpdatatable_23 AS t2
                WHERE t2.item = t1.item AND t2.`date` < t1.date 
                ORDER BY t2.`date` DESC LIMIT 0,1) AS difference
FROM wpdatatable_23 AS t1 
WHERE date IN (SELECT max(date) 
               FROM wpdatatable_23 
               GROUP BY item ) 
上一篇:rsync同步工具


下一篇:c – QProcess :: kill()和QProcess :: terminate()之间有什么区别?