SQL 查询 redshift 以获取第一个和最后一个值

SQL query on redshift to get the first and the last value

我有这样的数据集。

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

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

我用过下面的代码

 rank() OVER( PARTITION BY SessionID
            , VisitID

        ORDER by
            date_Time DESC ) as click_rank_last
where click_rank_last = 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