【问题标题】:comparing 2 rows + grouping Mysql比较2行+分组Mysql
【发布时间】:2016-03-30 18:58:53
【问题描述】:

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

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

【问题讨论】:

  • 真正的问题是什么?
  • 对不起,你现在可以看到了
  • 到目前为止您尝试过什么?如果答案只是想“我迷路了”,那么您需要聘请一名程序员为您做这件事。

标签: mysql sql


【解决方案1】:
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%'

【讨论】:

  • 这将是一个缓慢的查询 xD,如果你想快速聘请程序员
猜你喜欢
  • 2021-10-21
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 2014-11-01
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多