如何编写SQL查询来组合单个表的多行的特定列?

时间:2016-06-23 16:23:04

标签: sql oracle

我需要编写一个Oracle SQL查询。我有一个表名停止:

并且有两行如下:

STOP_ID LOCATION CONTRACT STOP_ORDER PICKUP_DT (IN TIME) DROP_DT (OUT TIME)
-----------------------------------------------------------------------------  
183     ABC         507     1    6/20/2016 6:25:00 AM    6/20/2016 6:25:00 AM 
184     CSD         507     2    6/20/2016 9:20:00 AM    6/20/2016 9:20:00 AM

现在我想以这种方式输出,我需要显示从位置CYB到BNY的(进出时间)。

输出中BNY的CYB和OUT时间的IN时间

CONTRACT  PICKUP_DT (IN TIME)  DROP_DT (OUT TIME)  LOCATION
--------------------------------------------------------------
507      6/20/2016 6:25:00 AM  6/20/2016 9:20:00 AM  CYB->BNY

请帮忙

我需要在停止表中另外一列create_date的基础上,针对过去两年停止表中存在的所有合同ID的查询输出。

标准与我解释的相同,对于每个合同ID,将有两个停靠点(1和2)。

2 个答案:

答案 0 :(得分:2)

select c1.contract, c1.pickup_dt, c2.drop_dt, c1.location||'->'||c2.location
from stops c1
inner join stops c2 on ( c1.contract = c2.contract)
where c1.contract = 507
and c1.stop_order =1 
and c2.stop_order = 2

答案 1 :(得分:0)

如果您想使用分析功能,这是一个解决方案。这避免了自我连接。

select contract, pickup_dt, drop_dt, location
from (
select contract
    , lag(pickup_dt) over (partition by contract order by stop_order) pickup_dt
    , drop_dt
    , stop_order
    , location || '->'||lag(location) over (partition by contract order by stop_order) location
from stop)
where stop_order = 2