dqzgzjwzzc 2017-10-25 03:10 采纳率: 50%
浏览 704

SQL查询语句的一点困惑

我有一张地铁站表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语句呢
_

  • 写回答

2条回答 默认 最新

  • 鱼在沙漠 2017-10-25 03:30
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog