【问题标题】:Add new rows with identical value except for one column添加除一列外具有相同值的新行
【发布时间】:2021-11-02 21:05:10
【问题描述】:

我对 SQL 还是很陌生,我不知道这是否可能。 所以我有这个航班行程表,我需要计算每条路线的航班数量。问题是往返航班使计算返程航班变得更加困难。表格是这样的:

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

我只想把桌子变成:

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 结合起来,然后按它分组以计算每条路线的总行程。

感谢您之前的努力回答这个问题!

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: sql insert duplicates rows


【解决方案1】:

你可以使用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';

注意:如果表中可能已经存在行并且您想避免重复,可以添加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
                     );

【讨论】:

  • 非常感谢!!!它工作得很好,我得到了想要的结果。
猜你喜欢
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 2016-11-29
  • 1970-01-01
相关资源
最近更新 更多