我有一张地铁站表Subway,如下
ticker_id txn_time txn_station trans_code
卡号 时分秒 站牌 进站或出站
比如
001 102520 101 0
001 114000 109 1
002 121102 105 0
002 131102 121 1
001 120055 109 0
001 140343 116 1
表示一个人在101进站,在109出站。
我现在想查询出他的进出站表,
select first.ticker_id, first.txn_station as station1, second.txn_station as station2, from Subway first,Subway second
where first.ticker_id=second.ticker_id and first.trans_code='0' and second.trans_code='1'
但是遇到一个问题,假如一个人进站多次并出站多次,
查询出来的结果就会不正确,如上面的表,
我希望的结果是:
ticker_id station1 station2
001 101 109
001 109 116
002 105 121
而实际的结果是_
ticker_id station1 station2
001 101 109
001 109 116
001 101 116
001 109 109
002 105 121
进出站应该是按时间匹配,第一个进站和第一个出站匹配,第二个进站和第二个出站匹配
请问该怎样正确的写这条sql语句呢
_
select ticker_id,in_stat,out_stat from (select a.ticker_id,a.txn_station as in_stat,b.txn_station as out_stat,min(b.txn_time-a.txn_time) from (select * from Subway where trans_code=0) a,(select * from Subway where trans_code=1) b where a.ticker_id=b.ticker_id and b.txn_time > a.txn_time group by a.ticker_id,a.txn_station) c
给你提供下思路。
第一步,一个人进出站多次,但人是唯一的,所以首先以人为单位进行分组。
第二小,分组后,需要处理的就是一个人的进出站先后顺序问题,这里可以使用层次查询来解决。