【问题标题】:SQL query to determine if events happen out of chronological order用于确定事件是否按时间顺序发生的 SQL 查询
【发布时间】:2022-01-22 07:27:17
【问题描述】:

我是 SQL 新手。我正在尝试编写一个查询来告诉我某些事件是否比第一个事件更早发生(即对于每个 ID,firstEvent 时间应该首先出现,然后是 secondEvent 时间,等等)。

每个事件都是一个对象,时间是 AVRO 类型的时间戳(在实际的 Java 代码中,它是一个 Instant)。这是目前的查询,但它只产生空白单元格:

select * from ( 
    select * from (
        select t.id as id,
            t.firstEvent.time as firstTime,
            t.secondEvent.time as secondTime,
            t.thirdEvent.time as thirdTime,
            t.fourthEvent.time as fourthTime,
        from avroTable t
        where t.firstEvent.time is not null
        ) allTimesT
    where (
        allTimesT.firstTime > allTimesT.secondTime 
        or allTimesT.firstTime > allTimesT.thirdTime
        or allTimesT.firstTime > allTimesT.fourthTime
    )
) finalT

如果我只查找不为空的 firstEvent 时间,则查询有效,但一旦我点击 where...or 块,它只会给我空白。

我想知道是否没有任何数据符合这些条件,所以我尝试切换运算符并执行allTimesT.firstTime < allTimesT.secondTime(预期的情况),但这也给了我空白单元格。有什么想法吗?

编辑:以下是一些示例数据:

【问题讨论】:

  • 你能展示一些示例数据吗?
  • 各种时间列中是否可以包含空值?如果可以,那么您可能需要在代码中明确允许这样做
  • @HoneyBadger 刚刚添加。这是为了工作,所以不是真实数据,但格式相同
  • @NickW 是的,很多列都有空时间值

标签: sql hive avro


【解决方案1】:

这样的东西会起作用吗?我不知道 Hive,所以你可能需要稍微调整一下:

with data as (
    select t.id as id,
        coalesce(t.firstEvent.time, t.secondEvent.time, t.thirdEvent.time, t.fourthEvent.time, '99991231') as time1,
        coalesce(t.secondEvent.time, t.thirdEvent.time, t.fourthEvent.time, '99991231') as time2,
        coalesce(t.thirdEvent.time, t.fourthEvent.time, '99991231') as time3,
        coalesce(t.fourthEvent.time. '99991231') as time4
    from avroTable t
)
select *
from data
where time1 > time2 or time2 > time3 or time3 > time4;
where 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多