我有一张包含以下日期和价值的表格。我需要根据日期[最大日期值 - 最小日期值]减去这些值并创建一个表格。
date value
2014-11-07 229275
2014-11-24 138746
2014-12-17 127112
预期输出为:
maxdate mindate value
2014-12-17 2014-11-07 102163
答案 0 :(得分:1)
如果你可以使用max(value)和min(value),那么很容易:
select max(date) as maxdate, min(date) as mindate, max(value) - min(value)
from table;
这适用于您的示例。
假设您确实需要最小日期和最大日期的值,请尝试改为:
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;