简体   繁体   English

根据Mysql同一行中的另一个值减去值

[英]Subtract values based on another value in same row in Mysql

I have a table with following date and value. 我有一张下面的日期和值的表格。 I need to subtract the values based on the date[max date value - min date value] and create a table. 我需要减去基于date [最大日期值-最小日期值]的值并创建一个表。

   date    value
2014-11-07 229275
2014-11-24 138746
2014-12-17 127112

The intended output is: 预期的输出是:

maxdate    mindate     value
2014-12-17 2014-11-07 102163

If you could use max(value) and min(value), then it would be easy: 如果可以使用max(value)和min(value),那将很容易:

select max(date) as maxdate, min(date) as mindate, max(value) - min(value)
from table;

This happens to work for your example. 这恰好适用于您的示例。

Assuming you really want the value on the min date and on the max date, try this instead: 假设您确实想要最小日期和最大日期上的值,请尝试以下操作:

select maxt.date as maxdate, mint.date as mindate, (mint.value - maxt.value) as diff
from (select t.* from table t order by date limit 1) as mint cross join
     (select t.* from table t order by date desc limit 1) as maxt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM