2013-08-19 68 views
1

乾杯, 工作Postgres的表行聚合的基於距離

CREATE TABLE my_table (
    "id" serial, 
    "sensorid" integer, 
    "actorid" integer, 
    "timestamp" timestamp without time zone, 
) 

與例如數據

id, sensorid, actorid, timestamp 
1; 2267; 3023; "2013-07-09 12:20:06.446" 
2; 2267; 3023; "2013-07-09 12:20:16.421" 
3; 2267; 3023; "2013-07-09 12:20:30.661" 
4; 2267; 3023; "2013-07-09 12:20:36.958" 
5; 2267; 3023; "2013-07-09 12:20:49.508" 
6; 2267; 3023; "2013-07-09 12:20:57.683" 
7; 3301; 3023; "2013-08-15 06:03:03.428" 
8; 2267; 3024; "2013-07-09 12:19:52.196" 
9; 2267; 3024; "2013-07-09 12:20:16.515" 
10; 2267; 3024; "2013-07-09 12:20:42.341" 
11; 2267; 3025; "2013-07-09 12:21:05.98" 
12; 2268; 3026; "2013-07-09 12:22:35.03" 
13; 2268; 3026; "2013-07-09 12:22:45.066" 
14; 3192; 3026; "2013-08-09 07:41:31.206" 

欲組用以下標準中的記錄

  1. 他們有相同的sensorid
  2. 他們有th e相同的演員
  3. (問題:)他們之間的時間跨度小於(說)5分鐘。也就是說,可能有一個小組跨越了一個多小時,但組中兩條記錄之間的間隔不超過5分鐘。時間跨度可以是平均的聚合。
  4. 此外,必須給出每個組的聚合記錄的數量,因爲必須標識太大的組。

因此,輸出應該是這個樣子

id; sensorid, actorid, avg, count 
1; 2267; 3023; "2013-07-09 12:20:30.000"; 7; 
2; 3301; 3023; "2013-08-15 06:03:03.428"; 1; 
3; 2267; 3024; "2013-07-09 12:20:06.415"; 3; 
5; 2267; 3025; "2013-07-09 12:21:05.98"; 1; 
6; 2268; 3026; "2013-07-09 12:22:40.626"; 2; 
7; 3192; 3026; "2013-08-09 07:41:31.206"; 1; 

感謝您的幫助! Dennis

+0

你應該接受戈登 - linoff答案。 –

回答

2

首先,您要使用lag()來確定上一次是否以及是否啓動新的期間。然後,對於每個感官/演員ID組合,您可以累積總和isStart來識別每對的組。

然後做彙總,包括結果這個新團體:

select sensorid, actorid, min(timestamp), max(timestamp), count(*) as numInGroup 
from (select t.*, 
      sum(isStart) over (partition by sensorid, actorid order by timestamp) as grp 
     from (select t.*, 
        (case when prevts is null or prevts < timestamp - interval '5 minutes' 
         then 1 else 0 
        end) as isStart 
      from (select t.*, 
         lag(timestamp) over (partition by sensorid, actorid 
               order by timestamp) as prevts 
        from my_table t 
       ) t 
      ) t 
    ) t 
group by sensorid, actorid, grp 
+0

嗨戈登,我沒有充分測試它,但現在看起來很完美(除了包括滯後函數調用[timestmp!= timestamp])在內的一個小錯字。顯然,我得到的結果比我預期的還要好。額外的時間段爲進一步分析提供了很好的機會。感謝您的回覆! – Ronk