2012-01-20 8 views
0

私はこのスキーマを持つテーブルを持っている:SQLクエリ取得グルー​​プは

enter image description here

コンテキストが同じ日に旅行している人とほぼ同じ時間です。私はそれから取得する必要がどのような

は次のとおりです。似た日付(diferenceの2 +/-時間最大)同じ場所と同じ型を持っているし、彼らは一緒に2回以上出現しなければならない人々の
グループその制約。

上記の画像で、JohnとSteveはクエリのすべての要件を共有しているため、結果に表示されます。

ありがとうございます。

+0

この問題は、各エントリごとにグループ化し、その単一エントリの範囲内にある行を見つける必要があるようです。しかし、再びあなたが任意のメジアン時間を使用する場合、これはさらに難しくなります。行われる必要があるのは、おそらく各 "グループ"の正確な論理要件の説明です。 –

+0

どのRDBMS(Oracle、SQLServer、MySQLなど)はこれですか?日付関数/演算子はRDBMSによって異なりますので、これが答えに影響します。 –

+0

また、あなたは試したことがありますか? – JNK

答えて

1

あなたが言うように、SQL Server 2008にすべてのテーブルを移行します。 その後、このクエリは2人のグループのためにあなたを助けることができる:

select t1.pesonId as Person1, t2.personId as Person2 
from 
    yourTable as t1 
    inner join 
    yourTable as t2 
    on 
     t2.PersonId > t1.PersonId and --to avoid t1,t2 and t2,t1 
     t2.Place = t1.Place and 
     t2.Type = t1.type and 
     t2.date between dateadd(hh, -2, t1.date) and dateadd(hh, +2, t1.date) 
group by 
    t1.pesonId, t2.personId 
having count(*) > 1 --more than one time as you say 

次に、このクエリは3人のグループのためにあなたを助けることができる:

select t1.pesonId as Person1, t2.personId as Person2,, t3.personId as Person3 
from 
    yourTable as t1 
    inner join 
    yourTable as t2 
    on 
     t2.PersonId > t1.PersonId and 
     t2.Place = t1.Place and 
     t2.Type = t1.type and 
     t2.date between dateadd(hh, -2, t1.date) and dateadd(hh, +2, t1.date) 
    inner join 
    yourTable as t3 
    on 
     t3.PersonId > t2.PersonId and 
     t3.Place = t1.Place and 
     t3.Type = t1.type and 
     t3.date between dateadd(hh, -2, t1.date) and dateadd(hh, +2, t1.date) 
group by 
    t1.pesonId, t2.personId, t3.personId 
having count(*) > 1 --more than one time as you say 

私はtested first query in data taking Post as your table、ここにデ結果を持っています:あなたがSSASを使用するか、knimeなどのデータマイニングツールに移動するには、より精巧な分析のために

Person1 Person2  
------- ------- --- 
22656 23354 584 
22656 29407 237 
22656 23283 230 
22656 69083 189 
22656 57695 178 
157882 203907 177 
26428 131527 175 
20862 131527 163 
22656 34397 159 
22656 65358 150 

(10 row(s) affected) 

私は示唆しています。

+0

00:00、01:00、04:00にレコードを検討してください。これらはすべて午前2時から+/- 2時間ですが、このクエリでは返されません。 – MatBailie

+0

なぜですか? @Dems、「02:00-2hと02:00 + 2hの間の00:00 = 00:00と04:00の間の00:00」=真! – danihp

+1

別のショートカットは... personA!= personB(PersonA、PersonB、PersonB、PersonAの結果を与える)の代わりに別の人が必要なので、PersonA DRapp

関連する問題