从MySQL计算每日温度梯度

时间:2015-02-19 13:33:58

标签: mysql date timestamp

请寻求以下问题的帮助。

我在计算太阳能加热水箱的日常温度梯度方面存在问题。基本上,我正试图计算出每天的温度损失率。

我有一个mysql数据库表,其中包含时间戳和坦克的当前temp(int),每5分钟存储一次。

timestamp          ¦   ct
2015-02-11 4:33    ¦   32
2015-02-11 3:33    ¦   32
2015-02-11 2:28    ¦   35
2015-02-11 1:23    ¦   51
2015-02-10 5:18    ¦   31
2015-02-10 4:13    ¦   31
2015-02-10 3:10    ¦   32
2015-02-10 2:58    ¦   33
2015-02-10 1:56    ¦33

e.g。 02-10的变化率(oC / min)为33-31 /(5:18-1:56)= 2/202mins = 0.0099 所以我希望查询返回

2015-02-10, 0.0099
2015-02-12, 0.1

到目前为止,我已设法找到每天的最小值和最大值,但未能在这两个最小值和最大值之间找到正确的时差。

select max(ct)- min(ct)as tempDiff, date(timestamp)
from homelog 
group by date(timestamp)
order by date(timestamp)

任何人都可以给我一个线索,了解如何计算出最小值和最大值出现的时间对应的时间戳,这样我就可以找出差异。我知道我可以使用timestampdiff,但不知道如何让值传递它。

谢谢

修改 感谢Gordon Linoff给我一个提示,我现在得到了以下内容

select date(maxTime),d1ct, d2ct, maxtime,mintime, timestampdiff(minute,maxTime,minTime),(d1ct-d2ct)/timestampdiff(minute,maxTime,minTime) from 
(select d1.ct as d1ct,min( h1.timestamp) as maxTime from 
(SELECT date(homelog.timestamp) as dte,MAX(ct) AS ct
FROM homelog
GROUP BY date(homelog.timestamp)
order by homelog.timestamp asc) d1
join homelog h1 on date(dte)=date(h1.timestamp)
and d1.ct = h1.ct
group by d1.ct, date(h1.timestamp)
order by h1.timestamp asc) d3
join 
(select d2.ct as d2ct,max( h3.timestamp) as minTime from 
(SELECT date(h2.timestamp) as dte2,min(ct) AS ct
FROM homelog h2
GROUP BY date(h2.timestamp)
order by h2.timestamp asc) d2
join homelog h3 on date(dte2)=date(h3.timestamp)
and d2.ct = h3.ct
group by d2.ct, date(h3.timestamp)
order by h3.timestamp asc ) d4 
on date(minTime)>=date(maxTime)
and date(minTime)<=date(maxTime)+ interval 1 day
where minTime>maxTime

最后的软糖,因为我知道我的最小温度总会在我的最大值的一天内发生,但对我有效。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

基本上,将您的查询用作子查询并加入信息:

select mm.*, maxct - minct as diff, hmin.timestamp, max.timestamp
from (select max(ct) as maxct, min(ct) as minct, date(timestamp) as dte
      from homelog 
      group by date(timestamp)
     ) mm join
     homelog hmin
     on date(hmin.timestamp) = mm.dte and hmin.ct = mm.minct join
     homelog hmax
     on date(hmax.timestamp) = mm.dte and hmax.ct = mm.maxct
order by dte;

当每天都有重复的最小值和最大值时,这会有一些问题。如果值实际上是浮点值,则很少发生这种情况。否则,您需要决定如何处理它们。我认为解释这个问题最好在另一个问题中完成,包括样本数据,期望的结果以及对你真正想做的事情的一个很好的解释。

答案 1 :(得分:0)

也许试试这个:

select date(l1.timestamp), max(l2.ct) - min(l1.ct) as deltaTemp, max(l2.timestamp) - min(l1.timestamp) as deltaTime
from homelog l1
inner join homelog l2 on date(l1.timestamp) = date(l2.timestamp)
group by date(l1.timestamp)
having l1.ct = min(l1.ct) and l2.ct = max(l2.ct)