SQL查询以获取序列的首尾


通过以下查询...

select aa.trip_id,aa.arrival_time,aa.departure_time,aa.stop_sequence,aa.stop_id,bb.stop_name
from  OeBB_Stop_Times aa
left join OeBB_Stops bb on aa.stop_id = bb.stop_id

我得到下表:

SQL查询以获取序列的首尾

现在,我想要来自stop_sequence列的第一行和最后一行/值引用列trip_id,所以结果应该是:

SQL查询以获取序列的首尾

我该怎么做?

谢谢

heshenzhi0622 回答:SQL查询以获取序列的首尾

您可以执行子查询以获取最小值和最大值,并根据该数据进行联接。
像这样:

select aa.trip_id,aa.arrival_time,aa.departure_time,aa.stop_sequence,aa.stop_id,bb.stop_name
from  OeBB_Stop_Times aa
join (
   SELECT trip_id,max(stop_sequence) as max_stop,min(stop_sequence) as min_stop
   FROM OeBB_Stop_Times
   GROUP BY trip_di
) sub on aa.trip_id = sub.trip_id AND (aa.stop_sequence = sub.max_stop or aa.stop_sequence = sub.min_stop)
left join OeBB_Stops bb on aa.stop_id = bb.stop_id
,

您可以两次使用ROW_NUMBER()窗口函数来过滤出行,如下所示:

select *
from (
  select *,row_number() over(partition by trip_id order by arrival_time) as rn,row_number() over(partition by trip_id order by arrival_time desc) as rnr
  from OeBB_Stop_Times
) x
where rn = 1 or rnr = 1
order by trip_id,arrival_time
,

您可以使用row_number()

select s.*
from (select st.trip_id,st.arrival_time,st.departure_time,st.stop_sequence,st.stop_id,s.stop_name,row_number() over (partition by st.trip_id order by st.stop_sequence) as seqnum_asc,row_number() over (partition by st.trip_id order by st.stop_sequence desc) as seqnum_desc
      from OeBB_Stop_Times st left join
           OeBB_Stops s
           on st.stop_id = s.stop_id
     ) s
where 1 in (seqnum_asc,seqnum_desc);

请注意,我修复了表别名,以便它们有意义而不是任意字母。

实际上,如果保证stop_sequence从1开始,这会更简单:

select s.*
from (select st.trip_id,max(stop_sequence) over (partition by st.trip_id) as max_stop_sequence
      from OeBB_Stop_Times st left join
           OeBB_Stops s
           on st.stop_id = s.stop_id
     ) s
where stop_sequence in (1,max_stop_sequence);
本文链接:https://www.f2er.com/3163895.html

大家都在问