小编典典

在特定日期使用sql / PHP计算两个不同行/列中两个数字的平均值,方差和标准差

sql

我有一个具有以下结构的数据库:

rowid       ID                  startTimestamp   endTimestamp   subject
1           00:50:c2:63:10:1a   ...1000          ...1090        entrance
2           00:50:c2:63:10:1a   ...1100          ...1270        entrance
3           00:50:c2:63:10:1a   ...1300          ...1310        door1
4           00:50:c2:63:10:1a   ...1370          ...1400        entrance
.
.
.

借助此SQL查询,我可以获得一行和下一行之间endTime和startTime之间的平均差异,并按主题和ID进行排序,并带有其最小值,最大值,方差和标准差:

SELECT ID,AVG(diff) AS average,
   AVG(diff*diff) - AVG(diff)*AVG(diff) AS variance,
   SQRT(AVG(diff*diff) - AVG(diff)*AVG(diff)) AS stdev,
   MIN(diff) AS minTime,
   MAX(diff) AS maxTime

FROM
(SELECT t1.id, t1.endTimestamp,
        min(t2.startTimeStamp) - t1.endTimestamp AS diff
FROM table1 t1
INNER JOIN table1 t2
ON t2.ID = t1.ID AND t2.subject = t1.subject
AND t2.startTimestamp > t1.startTimestamp  -- consider only later startTimestamps
WHERE t1.subject = 'entrance'
GROUP BY t1.id, t1.endTimestamp) AS diffs
GROUP BY ID

如果我在同一天只有几行且时差较小,那么这可以很好地工作,您可以在此sqlfiddle中看到它:

http://sqlfiddle.com/#!2/6de73/1

但是当我在另一天有其他数据时,我得到了错误的值:

http://sqlfiddle.com/#!2/920b6/1

因此,我想计算每一天的平均,最小,最大,方差,标准差。

我知道有MySQL的DATE-Functions,但是我做不完…有人可以帮我吗?还是我必须编写一段可以处理此问题的PHP代码?


阅读 240

收藏
2021-04-22

共1个答案

小编典典

与将日期添加到中一样容易吗group by?以下是适用于MySQL和SQLite的语法,将日期基于结束时间并假定结束时间存储为日期时间:

SELECT ID, thedate, AVG(diff) AS average,
   AVG(diff*diff) - AVG(diff)*AVG(diff) AS variance,
   SQRT(AVG(diff*diff) - AVG(diff)*AVG(diff)) AS stdev,
   MIN(diff) AS minTime,
   MAX(diff) AS maxTime
FROM (SELECT t1.id, t1.endTimestamp, DATE(endtimestamp) as thedate,
             min(t2.startTimeStamp) - t1.endTimestamp AS diff
      FROM table1 t1 INNER JOIN
           table1 t2
           ON t2.ID = t1.ID AND t2.subject = t1.subject AND
              t2.startTimestamp > t1.startTimestamp  -- consider only later startTimestamps
     WHERE t1.subject = 'entrance'
     GROUP BY t1.id, t1.endTimestamp
    ) AS diffs
GROUP BY ID, thedate

如果存储为时间戳,请参阅Marty的注释。

2021-04-22