【问题标题】:postgreSQL: Trying to filter out duplicate rows where the same location is showing but the timestamps slightly differ?postgreSQL:试图过滤掉显示相同位置但时间戳略有不同的重复行?
【发布时间】:2019-07-06 18:19:10
【问题描述】:

我正在使用具有“virtual_time”和“store_visited”字段的数据集,数据显示了用户在不同时间戳期间在不同位置的活动模式。

问题是有时用户可能在同一个位置,但同一地点的多个不同记录在数据集上更新,时间戳略有不同。

我正在尝试将这些较小的时间戳按位置分组在一起,这样数据对我来说更有意义,我以后可以区分用户在每个位置花费了多少时间。

例如当我输入时:

SELECT DISTINCT virtual_time, store_visited
FROM public.consumer
WHERE user = 'e63a9'
ORDER BY 1;

我得到了类似的东西:

    Store_visited   virtual_time
  1 M&S          2017-09-16 17:52:06
  2 WholeFoods   2017-09-16 18:26:17
  3 WholeFoods   2017-09-16 18:26:19
  4 WholeFoods   2017-09-16 18:26:20
  5 OysterRooms  2017-09-18 13:31:39

但我想过滤掉从第 3,4 行访问的重复商店,因为它们显示相同的位置,仅显示 2 秒和 1 秒的时间差。

理想情况下,过滤它会显示如下内容:

    Store_visited   virtual_time
   1 M&S          2017-09-16 17:52:06
   2 WholeFoods   2017-09-16 18:26:17
   5 OysterRooms  2017-09-18 13:31:39

这样更容易区分不同商店的不同时间戳。

希望这有点道理。任何帮助将不胜感激!

如果您有任何问题,请告诉我!

非常感谢

【问题讨论】:

  • 这是一个衍生的差距和孤岛问题,适合任何想尝试答案的人。
  • 我想我不能清楚地理解:“但我想过滤掉从第 3,4 行访问的重复商店,因为它们显示相同的位置,仅显示时差比如 2 秒和 1 秒”,因为您在输出中描述的内容可以通过以下方式完成:SELECT MIN(virtual_time), store_visited FROM public.consumer ... GROUP BY stored_visited

标签: sql postgresql filter timestamp


【解决方案1】:

这是喘息和孤岛问题。你可以使用Row_Number Function解决这个问题

来自文档:

当前行在其分区内的编号,从 1 开始计数

select
    store_visited,
    virtual_time
from
    (select 
          store_visited, 
          virtual_time, 
          row_number() over(partition by store_visited order by virtual_time asc) as vt
      from
          tbl) as new
where
    vt = '1'
order by
    virtual_time;

对于Demo<>Fiddle

【讨论】:

    【解决方案2】:

    您可以将时间戳四舍五入到分钟:

    select distinct store_visited, date_trunc('minute', virtual_time) as virtual_time
    from consumer
    order by 2;  
    

    这是最快但不是很准确的解决方案。更好的方法是检查连续行之间的差异并跳过特定范围内的差异。使用window function lag():

    select store_visited, virtual_time
    from (
        select 
            store_visited, virtual_time, 
            coalesce(virtual_time- lag(virtual_time) over w < '10 seconds', false) as neglible
        from consumer
        window w as (partition by store_visited order by virtual_time)
        ) s
    where not neglible
    order by 2;  
    
     store_visited |    virtual_time     
    ---------------+---------------------
     M&S           | 2017-09-16 17:52:06
     WholeFoods    | 2017-09-16 18:26:17
     OysterRooms   | 2017-09-18 13:31:39
    (3 rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多