【问题标题】:How to establish a ranking of column based on time series如何建立基于时间序列的列排名
【发布时间】:2019-12-31 17:26:00
【问题描述】:

我有一个需要一些特殊情况的数据集。我有一个位置历史记录表,需要:

  1. 按每个唯一 ID 的交易日期排名
  2. 找到一种方法来判断该行是否与位置 X 对应
  3. 提取位置 X 存在的所有行,如果 AFTER 行与位置 X 不同
  4. 不返回位置 X 是唯一 ID 中最后一行的行

示例数据:

ID  Location    Transaction_Dt
1   Location 1  1/1/2019
1   Location X  1/2/2019
1   Location 3  1/3/2019
2   Location 4  1/5/2019
2   Location 5  1/6/2019
2   Location X  1/7/2019
3   Location X  1/8/2019
3   Location 6  1/9/2019
3   Location 7  1/10/2019

所以这个例子:

  1. 唯一 ID 1 将表明 ID 在位置 X 之后转到位置 3
  2. 唯一 ID 2 不会返回任何内容,因为位置 X 是唯一 ID 的最后一个
  3. 唯一 ID 3 将显示 ID 在位置 7 之后到达位置 6(不需要显示位置 7,只需显示位置 X 之后的行)

我熟悉 RANK() 和 Partition By,但似乎无论我尝试什么都没有给我正确的排名。我想我可能需要重新加入表格才能获得所需的结果。

我目前正在使用 Aginity SQL,并且也有 R 的背景,所以无论哪种方式,这对我来说都很好。

【问题讨论】:

  • 请编辑您的问题并显示您想要的结果。

标签: sql r time time-series rank


【解决方案1】:

这是你想要的吗?

select t.*
from (select t.*,
             lag(location) over (partition by id order by Transaction_Dt) as prev_id
      from t
     ) t
where prev_id = 'X' or prev_id is null and
      id <> 'X';

【讨论】:

    【解决方案2】:

    这是一种方法

    with tlog as (
        select ID, Location, cast(dts as date) Transaction_Dt
        from (values
         (1,'Location 1','1/1/2019')
        ,(1,'Location X','1/2/2019')
        ,(1,'Location 3','1/3/2019')
        ,(2,'Location 4','1/5/2019')
        ,(2,'Location 5','1/6/2019')
        ,(2,'Location X','1/7/2019')
        ,(3,'Location X','1/8/2019')
        ,(3,'Location 6','1/9/2019')
        ,(3,'Location 7','1/10/2019')
        ) t (ID,Location, dts) 
    )
    select ID, Location, Transaction_Dt, rnk
    from (
        select ID, Location, Transaction_Dt
            , rank() over(partition by id order by Transaction_Dt) rnk /* 1 */
            , lag(Location, 1, '') over(partition by id order by Transaction_Dt) prevLoc
            , last_value(Location) over(partition by id order by Transaction_Dt rows between current row and unbounded following) lastLoc
        from tlog) t
    where 'Location X' not in(lastLoc /* 4 */ , Location /* 3 */ ) and prevLoc = 'Location X'/* 2, 3 */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多