我是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#|起源| DESTINATION1 | DESTINATION2
1 |悉尼| MELBORUNE | ADELAIDE
原点是DEPARTURE
DESTINATION1可以是DEPARTURE
或DESTINATION
DESTINATION2是DESTINATION
。
查询应包含COUNT(T#) < 3
,因为我只需要显示小于3的记录。如何通过2个关系视图来实现此结果?
答案 0 :(得分: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
答案 1 :(得分: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';
<强>解释强>
答案 2 :(得分: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;