2012-03-24 103 views
1

我想查詢我的連接歷史表成小時時間框架,每小時它的連接持續時間。分組時間範圍的sqlite查詢

create table sessionHistory (
    _id  integer PRIMARY KEY autoincrement, 
    modified integer, 
    ip  text, 
    ... 
    started integer, 
    ended  integer 
); 

每個連接開始都有一個「開始」的日期,當它結束時,我把一個「結束」日期,都在unix時代。

我能夠將它們分組使用以下查詢:

select strftime('%H', started, 'unixepoch') HOUR_, 
     sum(ended-started) TOTAL_TIME_ 
from sessionHistory 
where ip='123.123.123.123' and ended!=0 
group by strftime('%H', started, 'unixepoch') 

現在,我還希望在每一個小時,包括會議時間仍然持續(截至= 0)。

例如,在小時1,連接已經開始並且以35秒的持續時間結束。在2小時的連接已經開始只是變成3小時,以10秒鐘做轉彎前,並變成小時3

這意味着查詢需要返回類似小時1 => 35後停止10秒,小時2 => 10,小時3 => 10。 此外,如果連接仍處於結束狀態(結束= 0),我想讓當前小時保存「now」開始的數據,這會在相對小時內累積。

加入2個sqlite查詢將不會回答最後一個規範,因爲它總是會返回「now」 - 「started」,即使會話超過1小時。

回答

4
select strftime('%H', started, 'unixepoch') HOUR_, 
     sum(ended-started)+ 
      (
      SELECT sum(now-started) 
      from sessionHistory 
      where ip='123.123.123.123' and ended=0 
      group by strftime('%H', started, 'unixepoch') 
      ) TOTAL_TIME_ 
from sessionHistory 
where ip='123.123.123.123' and ended!=0 
group by strftime('%H', started, 'unixepoch')