比较2行+分组Mysql

时间:2016-03-30 18:58:54

标签: mysql sql

我该怎么做?我搞不清楚了。

╔════════╦══════════╦══════════╗
║ 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 ║
╚════════╩══════════╩══════════╝

输出应显示每种类型中的一个项目,其中包含与上一行的最后价格和价格差异

╔════════╦══════════╦════════════════════════╗
║ ITEM   ║ PRICE    ║ DATE     ║ Differnece  ║
╠════════╬══════════╬════════════════════════╣
║ Dollar ║       50 ║ 2.3.2016 ║   -10       ║
║ Bound  ║      110 ║ 2.3.2016 ║    10       ║
║ Euro   ║      580 ║ 3.3.2016 ║   -20       ║
╚════════╩══════════╩════════════════════════╝

1 个答案:

答案 0 :(得分:0)

select name as 'Item',
       price as 'Price',
       (select max(date) from table where name like '%dollar%') as 'Date',
       (select top 1 price from table where name like '%dollar%') - (select top 1 price from table where id< (select max(id) from table where name like '%dollar%')and name like '%dollar%' order by id desc) as 'difference'
       from table where name like '%dollar%'
union all --now just repeat the code above and switch the like as you want
select name as 'Item',
       price as 'Price',
       (select max(date) from table where name like '%bound%') as 'Date',
       (select top 1 price from table where name like '%bound%') - (select top 1 price from table where id< (select max(id) from table where name like '%bound%')and name like '%bound%' order by id desc) as 'difference'
       from table where name like '%bound%'