使用sqlite / php获取两个不同行/列中的两个数字的差异

时间:2013-01-19 19:37:44

标签: php mysql sql select

我有一个带有名为“events”的表的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中编写一段代码?

3 个答案:

答案 0 :(得分: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 ;

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

尝试此操作:不确定是否要使用abs,而是相应地进行调整。在我的示例中,我只使用了前几行。但是,如果您想使用不同的数据,那么您可以将适当的id值添加到where condition

SQLFIDDLE DEMO

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 |