SQL过滤器 - 使用多个列的组合进行过滤

时间:2016-10-22 04:20:08

标签: sql postgresql

表1

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

伪代码

  1. 使用过滤器zipcode, timestamp_hour创建device='pc'组合的临时表,以获得符合条件的zipcode, timestamp_hour列表
  2. 将#1应用为table1
  3. 的过滤器

    对于上面的#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
    )
    

2 个答案:

答案 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.devicezipcode的所有条目hour,但仅保留t2.devicepc的条目。 <{1}}关键字需要清除重复的条目。