Redshift上的SQL查询以获取第一个和最后一个值

Posted

技术标签:

【中文标题】Redshift上的SQL查询以获取第一个和最后一个值【英文标题】:SQL query on redshift to get the first and the last value 【发布时间】:2019-03-06 13:22:33 【问题描述】:

我有一个这样的数据集。

我需要编写一个查询,它会给出以下输出

对于每个 SessionID 和 VisitID,它应该根据 date_time 列进行排序,并为我提供第一个类别和最后一个类别。

我使用了以下代码

 rank() OVER( PARTITION BY SessionID
            , VisitID

        ORDER by
            date_Time DESC ) as click_rank_last
where click_rank_last = 1

获取最后一个类别。但我需要的是在单个查询中获取第一个和最后一个,对数据库的影响最小,因为数据量很大并且查询成本很高。

需要最优化的查询!

【问题讨论】:

【参考方案1】:

一种方法是:

select distinct
       sessionid,
       visitid,
       first_value(category) over (
            partition by sessionid, visitid
            order by date_time
            rows between unbounded preceding and unbounded following),
       last_value(category) over (
            partition by sessionid, visitid
            order by date_time
            rows between unbounded preceding and unbounded following)
from   tbl

【讨论】:

以上是关于Redshift上的SQL查询以获取第一个和最后一个值的主要内容,如果未能解决你的问题,请参考以下文章