1

我有一个带有名为“事件”的表的 SQLite 数据库,它具有以下结构:

rowid       ID                  startTimestamp   endTimestamp
1           00:50:c2:63:10:1a   1000             1010
2           00:50:c2:63:10:1a   1100             1030
3           00:50:c2:63:10:1a   1090             1110   
4           00:50:c2:63:10:1a   1210             1310
.
.
.

计算 startTimestamp 和 endTimestamp 之间的平均时间是没有问题的:

SELECT ID, avg(endTimestamp - startTimestamp) AS duration FROM events WHERE senderID ="00:50:c2:63:10:1a"

但是现在我想在一行和下一行之间计算 endTime 和 startTime 之间的平均差异,这对于我的示例来说意味着:

1100-1010 = 90

1090-1030 = 60

1210-1110 = 100


差值之和 = 90 + 60 + 100 = 250

平均差 = 250 / 3 = 83,33

有没有办法用 SQL 查询来做到这一点?或者是否有必要用 PHP 编写一段代码?

4

3 回答 3

1
SELECT
    id,
    ( MAX(endtimestamp) - MIN(startTimestamp)
    - SUM(endtimestamp-startTimestamp)
    ) / (COUNT(*)-1) AS averageDifference
FROM
    events
GROUP BY
    id ;

在 SQL-Fiddle 测试:test-1(感谢@bonCodigo)


由于MIN(endtimestamp)可能不是最低rowid的,因此上述查询需要更正

SELECT
    id,
    ( ( SELECT endtimestamp FROM events AS ee 
        WHERE ee.id = e.id ORDER BY rowid ASC LIMIT 1 )
    - ( SELECT startTimestamp FROM events AS ee
        WHERE ee.id = e.id ORDER BY rowid DESC LIMIT 1 )
    - SUM(endtimestamp-startTimestamp)
    ) / (COUNT(*)-1) AS averageDifference
FROM
    events AS e
GROUP BY
    id ;
于 2013-01-19T20:10:22.037 回答
0

试试这个:

SELECT id,( SUM(duration) / COUNT(*) ) duration
FROM (SELECT ID, (endTimestamp - startTimestamp) AS duration 
      FROM events WHERE senderID ="00:50:c2:63:10:1a")
于 2013-01-19T19:42:18.500 回答
0

试试这个:不确定是否要使用abs,但要进行相应的调整。在我的示例中,我只使用了您的前几行。但是,如果您想使用不同的数据,则可以将正确的id值添加到where condition

SQLFIDDLE 演示

select id, 
sum(abs(endtimestamp - starttimestamp))/Count(*) 
as span from table1
where id = '00:50:c2:63:10:1a'
group by id
;

样本表中所有 ID 的结果:

|                ID | SPAN |
----------------------------
| 00:50:c2:63:10:1a |   50 |
| 00:50:c2:63:10:2a |  100 |
于 2013-01-19T19:51:27.660 回答