person | zipcode | timestamp | event | device
--------------------------------------------------|--------|------
amar | 11111 | 2016-09-28 20:05:03.001 | email | phone
akbar | 11111 | 2016-09-28 20:05:03.001 | email | phone
antony | 11111 | 2016-09-28 20:07:03.001 | chat | pc
amar | 11111 | 2016-09-28 20:08:03.001 | email | phone
amar | 11111 | 2016-09-28 20:08:03.001 | chat | phone
amar | 22222 | 2016-09-28 20:09:03.001 | email | phone
akbar | 22222 | 2016-09-28 20:10:03.001 | email | phone
antony | 22222 | 2016-09-28 20:10:03.001 | chat | phone
amar | 11111 | 2016-09-28 21:05:03.001 | email | phone
akbar | 11111 | 2016-09-28 21:05:03.001 | email | phone
antony | 11111 | 2016-09-28 21:07:03.001 | chat | phone
所需输出
记录
对于存在pc
设备的记录的所有小时的所有邮政编码
唯一符合条件的zipcode, timestamp_hour
组合是11111, 2016-09-28 20
person | zipcode | timestamp | event | device
--------------------------------------------------|--------|------
amar | 11111 | 2016-09-28 20:05:03.001 | email | phone
akbar | 11111 | 2016-09-28 20:05:03.001 | email | phone
antony | 11111 | 2016-09-28 20:07:03.001 | chat | pc
amar | 11111 | 2016-09-28 20:08:03.001 | email | phone
amar | 11111 | 2016-09-28 20:08:03.001 | chat | phone
伪代码
zipcode, timestamp_hour
创建device='pc'
组合的临时表,以获得符合条件的zipcode, timestamp_hour
列表table1
对于上面的#1,我的代码如下,需要#2
的帮助with zipcode_hour as (
select zipcode, date_trunc(`hour`, timestamp) as timestamp_hour
from table1
where device = 'pc'
group by zipcode, timestamp_hour
)
答案 0 :(得分:2)
您可以使用以下查询
SELECT person
,zipcode
,timestamp1
,event
,device
FROM table1 a
WHERE EXISTS (
SELECT 1
FROM table1 b
WHERE b.device = 'pc'
AND date_trunc('hour', a.timestamp1) = date_trunc('hour', b.timestamp1)
AND a.zipcode = b.zipcode
);
完整结果SQLFiddle
答案 1 :(得分:0)
您可以使用自联接和where子句
进行过滤select distinct t1.person, t1.zipcode, t1."timestamp", t1.event, t1.device
from table1 t1
join table1 t2 on t2.zipcode = t1.zipcode
and date_trunc('hour', t2."timestamp") = date_trunc('hour', t1."timestamp")
where t2.device = 'pc'
这会查找具有相同t1.*, t2.device
和zipcode
的所有条目hour
,但仅保留t2.device
为pc
的条目。 <{1}}关键字需要清除重复的条目。