添加除一列外具有相同值的新行
Add new rows with identical value except for one column
我对SQL还是很陌生,不知道是否可行。
所以我有这次飞行旅行table,我需要计算每条航线有多少航班。问题是有往返航班,这使得计算回程航班的路途变得更加困难。 table 是这样的:
source_id
destination_id
date
trip_type
AUH
MAN
2017-01-01
RoundTrip
LHR
CDG
2017-05-12
OneWay
DXB
BHX
2017-12-20
Roundtrip
我只想把 table 变成:
source_id
destination_id
date
trip_type
AUH
MAN
2017-01-01
RoundTrip
MAN
AUH
2017-01-01
RoundTrip
LHR
CDG
2017-05-12
OneWay
DXB
BHX
2017-12-20
Roundtrip
BHX
DXB
2017-12-20
Roundtrip
因此我可以稍后创建一个新列,将 source_id 和 destination_id 组合在一起,然后将其分组以计算每条路线的总行程。
在此之前感谢您的热心回答!
您可以使用 insert
:
insert into t (source_id, destination_id, date, trip_type)
select destination_id, source_id, date, trip_type
from t
where trip_type = 'Roundtrip';
注意:如果有可能行已经在table中,并且你想避免重复,你可以添加一个not exists
子句:
insert into t (source_id, destination_id, date, trip_type)
select destination_id, source_id, date, trip_type
from t
where trip_type = 'Roundtrip' and
not exists (select 1
from t t2
where t2.trip_type = t.trip_type and
t2.date = t.date and
t2.destination_id = t.source_id and
t2.source_id = t.destination_id
);
我对SQL还是很陌生,不知道是否可行。 所以我有这次飞行旅行table,我需要计算每条航线有多少航班。问题是有往返航班,这使得计算回程航班的路途变得更加困难。 table 是这样的:
source_id | destination_id | date | trip_type |
---|---|---|---|
AUH | MAN | 2017-01-01 | RoundTrip |
LHR | CDG | 2017-05-12 | OneWay |
DXB | BHX | 2017-12-20 | Roundtrip |
我只想把 table 变成:
source_id | destination_id | date | trip_type |
---|---|---|---|
AUH | MAN | 2017-01-01 | RoundTrip |
MAN | AUH | 2017-01-01 | RoundTrip |
LHR | CDG | 2017-05-12 | OneWay |
DXB | BHX | 2017-12-20 | Roundtrip |
BHX | DXB | 2017-12-20 | Roundtrip |
因此我可以稍后创建一个新列,将 source_id 和 destination_id 组合在一起,然后将其分组以计算每条路线的总行程。
在此之前感谢您的热心回答!
您可以使用 insert
:
insert into t (source_id, destination_id, date, trip_type)
select destination_id, source_id, date, trip_type
from t
where trip_type = 'Roundtrip';
注意:如果有可能行已经在table中,并且你想避免重复,你可以添加一个not exists
子句:
insert into t (source_id, destination_id, date, trip_type)
select destination_id, source_id, date, trip_type
from t
where trip_type = 'Roundtrip' and
not exists (select 1
from t t2
where t2.trip_type = t.trip_type and
t2.date = t.date and
t2.destination_id = t.source_id and
t2.source_id = t.destination_id
);