1

我有一个问题,这就是我所拥有的

SQL> desc trktripleg
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------

 T#                                        NOT NULL NUMBER(10)
 LEG#                                      NOT NULL NUMBER(2)
 DEPARTURE                                 NOT NULL VARCHAR2(30)
 DESTINATION                               NOT NULL VARCHAR2(30)

我尝试执行以下操作

SQL> select destination,departure from trktripleg where T#=15;

DESTINATION                    DEPARTURE
------------------------------ ------------------------------
Adelaide                       Melbourne
Melbourne                      Sydney

我怎么弄成这样...

SOURCE     DESTINATION   DESTINATION2

Adelaide   Melbourne    Sydney

假设只有 1 个目的地

SQL> select destination,departure from trktripleg where T#=11;

DESTINATION                    DEPARTURE
------------------------------ ------------------------------
Sydney                         Melbourne


SOURCE     DESTINATION   DESTINATION2

Adelaide   Melbourne    

我现在正在查看,就像我提供 T# 一样,它将显示源目的地出发

一些原始插入数据..

INSERT INTO TRKTRIPLEG VALUES(11, 1, 'Melbourne', 'Sydney');

INSERT INTO TRKTRIPLEG VALUES(15, 1, 'Sydney', 'Melbourne');
INSERT INTO TRKTRIPLEG VALUES(15, 2, 'Melbourne', 'Adelaide');

感谢所有帮助。我正在使用 oracle sql。

4

3 回答 3

2

如果我正确理解了您的架构,您可以这样做

 SELECT   t1.departure AS Source,
         t1.destination AS Destination1,
         t2.destination AS Destination2
  FROM      trktripleg t1
         LEFT OUTER JOIN
            trktripleg t2
         ON t2.T# = t1.T# AND t2.LEG# = 2
 WHERE   t1.LEG# = 1;

SQL 提琴示例

于 2012-11-26T10:42:27.867 回答
2
create table trktripleg
(
T#                                         NUMBER(10)NOT NULL
 ,LEG#                                       NUMBER(2) NOT NULL
 ,DEPARTURE                                  VARCHAR2(30) NOT NULL
 ,DESTINATION                                VARCHAR2(30) NOT NULL
  );

INSERT INTO TRKTRIPLEG VALUES(11, 1, 'Melbourne', 'Sydney');

INSERT INTO TRKTRIPLEG VALUES(15, 1, 'Sydney', 'Melbourne');
INSERT INTO TRKTRIPLEG VALUES(15, 2, 'Melbourne', 'Adelaide');

SELECT DEPARTURE
      ,DESTINATION
      ,DESTINATION_2
FROM
(
SELECT DEPARTURE
      ,DESTINATION
      ,LEAD(DESTINATION, 1, NULL) 
              OVER (partition by T# ORDER BY LEG#) DESTINATION_2
      ,LEG#
FROM trktripleg
)
WHERE LEG#=1

http://www.sqlfiddle.com/#!4/5b27c/11

于 2012-11-26T10:43:29.250 回答
0

你可以这样做..

select 
    t,
    MAX(source),
    max(destination),
    max(destination2)
from
(
    select t, departure as source, DESTINATION ,null as destination2 from yourtable where LEG = 1
    union all
    select t, null, null, destination from yourtable where LEG =2 
) p
group by t

更一般地说,您可以根据leg值进行数据透视。

于 2012-11-26T10:41:58.387 回答