【问题标题】:Return rows where one column is consistent but another changes within a time period返回一列一致但另一列在一段时间内发生变化的行
【发布时间】:2019-09-04 15:55:28
【问题描述】:

我试图找出计算机何时从一个访问点跳转到另一个访问点并在数据库中捕获数据。我每小时捕获一次数据,因此电脑名称会出现多次,但只有当电脑从一台切换到另一台时,应用程序才会更改。我需要返回一个示例查询。

我只想在最近 12 小时内计算机上的 ap 发生变化时返回一行。

我尝试从两个字段中选择不同的字段,然后将它们解析出来,但我相信必须有更好的方法。

示例表如下所示:

1 PC1 AP1 时间

2 PC2 AP1 时间

3 PC3 AP2 时间

4 PC4 AP2 时间

5 PC5 AP3 时间

6 PC1 AP1 时间

7 PC2 AP2 时间

8 PC3 AP2 时间

9 PC4 AP2 时间

10 PC5 AP3 时间

所以在这个例子中,唯一返回的信息应该是关于 PC2,因为它是唯一改变 AP 的单元,所以我会得到这两行(2 和 7)。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用lag()。在标准 SQL 中,这看起来像:

    select t.*
    from (select t.*, lag(app) over (partition by computer order by time) as prev_app
          from t
         ) t
    where prev_app <> app and
          time > current_datetime - interval '12 hour';
    

    众所周知,日期/时间功能取决于您使用的数据库,因此您的数据库的语法可能会有所不同。

    【讨论】:

      【解决方案2】:

      存在:

      select t.* from tablename t
      where exists (
        select 1 from tablename
        where computername = t.computername and ap <> t.ap 
        and time between dateadd(hour, -12, t.time) and dateadd(hour, 12, t.time)
      )
      

      【讨论】:

        猜你喜欢
        • 2017-06-09
        • 1970-01-01
        • 1970-01-01
        • 2020-01-18
        • 2018-04-21
        • 2021-01-15
        • 2020-12-01
        • 2023-01-10
        相关资源
        最近更新 更多