0

我是 SQL 新手,目前这是我正在尝试做的事情:将
多行数据显示到同一行中的不同列中

我有一张这样的桌子:

CREATE TABLE TRIPLEG(
    T#              NUMBER(10)      NOT NULL,
    LEG#            NUMBER(2)       NOT NULL,
    DEPARTURE       VARCHAR(30)     NOT NULL,
    DESTINATION     VARCHAR(30)     NOT NULL,
    CONSTRAINT TRIPLEG_PKEY PRIMARY KEY (T#, LEG#),
    CONSTRAINT TRIPLEG_UNIQUE UNIQUE(T#, DEPARTURE, DESTINATION),
    CONSTRAINT TRIPLEG_FKEY1 FOREIGN KEY (T#) REFERENCES TRIP(T#) );
INSERT INTO TRIPLEG VALUES( 1, 1, 'Sydney', 'Melbourne');
INSERT INTO TRIPLEG VALUES( 1, 2, 'Melbourne', 'Adelaide');

结果应该是这样的:

T# | 原产地 | 目的地1 | 目的地
2 1 | 悉尼 | 墨尔本 | 阿德莱德

起源是DEPARTURE.
DESTINATION1 可以是DEPARTUREOR DESTINATION
DESTINATION2 是DESTINATION.

查询应该包括,COUNT(T#) < 3因为我只需要显示小于 3 的记录。如何使用 2 个关系视图来实现此结果?

4

3 回答 3

1

请试试这个

select t#,regexp_substr(tree,'[^:]+',2) origin,
regexp_substr(tree,'[^:]+',2,2) destination1,
regexp_substr(tree,'[^:]+',2,3) destination2
from 
(
    select a.*, 
        sys_connect_by_path(departure,':') tree, 
        level lvl 
    from tripleg a
        connect by nocycle prior destination = departure and prior t# = t#
        start with leg# = 1
        and level < = 3
)
where lvl = 3;
于 2013-11-12T12:21:30.677 回答
1

您可以使用分层查询。

数据设置:

CREATE TABLE TRIPLEG ( T#   NUMBER ( 10 ) NOT NULL,
                   LEG# NUMBER ( 2 ) NOT NULL,
                   DEPARTURE VARCHAR ( 30 ) NOT NULL,
                   DESTINATION VARCHAR ( 30 ) NOT NULL );

INSERT INTO
      TRIPLEG
VALUES
      ( 1,
        1,
        'Sydney',
        'Melbourne' );

INSERT INTO
      TRIPLEG
VALUES
      ( 1,
        2,
        'Melbourne',
        'Adelaide' );

INSERT INTO
      TRIPLEG
VALUES
      ( 2,
        1,
        'A',
        'B' );

INSERT INTO
      TRIPLEG
VALUES
      ( 2,
        2,
        'B',
        'C' );

INSERT INTO
      TRIPLEG
VALUES
      ( 2,
        3,
        'C',
        'D' );

INSERT INTO
      TRIPLEG
VALUES
      ( 3,
        1,
        'A',
        'B' );

COMMIT;

询问:

SELECT
      T#,
      CONNECT_BY_ROOT DEPARTURE
      || SYS_CONNECT_BY_PATH ( DESTINATION,
                          ' ~ ' )
          AS ROUTE
FROM
      TRIPLEG
WHERE
      LEVEL = 2
CONNECT BY
      NOCYCLE DEPARTURE = PRIOR DESTINATION
START WITH
      T# = '1';

解释:

  1. 根据 Departure 和 Destination 之间的关系连接行。
  2. 过滤满足中转的行(严格)
  3. 不使用 LEG#。
于 2013-11-11T14:59:37.090 回答
1

尝试这个:

select t1.T#, 
       (select t2.departure from tripleg t2 where t1.T# = t2.T# and t2.LEG# = 1) Origin,
       (select t2.destination from tripleg t2 where t1.T# = t2.T# and t2.LEG# = 1) Destination1,
       (select t2.destination from tripleg t2 where t1.T# = t2.T# and t2.LEG# = 2) Destination2
  from tripleg t1
 group by t1.T#
having count(1) < 3
于 2013-11-11T11:56:49.053 回答