Same table, maximum group date by type, 2 row difference

How can i do this? I have this table

╔════════╦══════════╦══════════╗
β•‘ 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 β•‘
β•šβ•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•

The output should display one element from each type with the last default of the price on the last date and the price difference from the previous line, for example:

╔════════╦══════════╦════════════════════════╗
β•‘ item   β•‘ price    β•‘ date     β•‘ differnece  β•‘
╠════════╬══════════╬════════════════════════╣
β•‘ Dollar β•‘       50 β•‘ 2.3.2016 β•‘   -10       β•‘
β•‘ Bound  β•‘      110 β•‘ 2.3.2016 β•‘    10       β•‘
β•‘ Euro   β•‘      580 β•‘ 3.3.2016 β•‘   -20       β•‘
β•šβ•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

I did it ...


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

... and it works fine. I just don’t know how to make a difference, any help?

+4
source share
2 answers

You can calculate the difference using the correlated subquery:

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 ) 
+4
source

Check this out (a small modification of 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);
0
source

All Articles