我该怎么做?我有这张桌子
╔════════╦══════════╦══════════╗
║ 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
......它工作正常。我只是不知道如何做差异的事情,有什么帮助吗?
答案 0 :(得分:4)
您可以使用相关子查询来计算差异:
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 )
答案 1 :(得分:0)
检查一下(Giorgos SQL的小修改):
SELECT
a.item,
a.`date`,
a.price,
a.price - (SELECT price
FROM prices AS t2
WHERE t2.item = a.item AND t2.`date` < a.`date`
ORDER BY t2.`date` DESC LIMIT 0,1) as diff
FROM
prices AS a
WHERE
a.date = (SELECT MAX(date) FROM prices b WHERE b.item = a.item GROUP BY item);