如何从 SQL 中的两列获取唯一对

Unc*_*sse 4 mysql sql t-sql

我被困在http://www.sql-ex.ru/learn_exercises.php#answer_ref的练习 68 上。

该数据库由以下四个表组成:

  1. 公司(ID_comp,名称)
  2. 行程(行程编号、id_comp、飞机、城镇出发地、城镇目的地、超时、入时)
  3. 乘客(ID_psg, 姓名)
  4. Pass_in_trip(行程编号、日期、ID_psg、地点)

练习的目标是:找出航班(行程)数量最多的航线数量。笔记。

  1. A - B 和 B - A 被视为同一路由。
  2. 仅使用行程表。

我可以得到“找出航班(行程)数量最多的航线数量”的正确答案,但在考虑注释 1 时却无法得到正确答案:A - B 和 B - A 被视为同一航线。

我不知道如何获得唯一的对:如果我们有输出:

| town_from | town_to   | count |
| --------- | --------- | ----- |
| London    | Singapore | 4     |
| Singapore | London    | 4     |
Run Code Online (Sandbox Code Playgroud)

我如何选择才能只给我

| town_from | town_to   | count |
| --------- | --------- | ----- |
| London    | Singapore | 4     |
Run Code Online (Sandbox Code Playgroud)

我能够通过以下查询完成问题:

WITH x AS( SELECT con, sum(c) as s FROM( SELECTtown_from,town_to, 'con' = CASE WHEN lower(town_from)

SELECT count(*) FROM x WHERE s = (SELECT max(s) FROM x)

lc.*_*lc. 5

您需要以表示 from->to 的方式查看该Trip表,就像表示 to->from 一样。执行此操作的典型方法是确保它始终已排序town_from <(=) town_to

一般来说,下面的查询会Trip以这种方式投影。case 子句来回切换以保持它们始终排序:

select trip_no, id_comp, plane, 
    case when town_from < town_to then town_from else town_to end as town_from, 
    case when town_from < town_to then town_to else town_from end as town_to, 
    time_out, time_in
from Trip
Run Code Online (Sandbox Code Playgroud)

然后,您可以在查询中从此投影中进行选择:

select ...
from (
    select trip_no, id_comp, plane, 
        case when town_from < town_to then town_from else town_to end as town_from, 
        case when town_from < town_to then town_to else town_from end as town_to, 
        time_out, time_in
    from Trip
) as x
Run Code Online (Sandbox Code Playgroud)

为了解决这个特定问题,我们可以应用相同的逻辑,但删除不必要的列(优化器无论如何都应该这样做,但它对人眼来说看起来更干净):

select town_from, town_to, count(*)
from (
    select 
        case when town_from < town_to then town_from else town_to end as town_from, 
        case when town_from < town_to then town_to else town_from end as town_to 
    from Trip
) as x
group by town_from, town_to
Run Code Online (Sandbox Code Playgroud)

注意:如果我错了,请纠正我,但在您的预期输出中, London<->Singapore 的总数应该是8,而不是4。您在一个方向有 4 次行程,在另一个方向有 4 次,总共 8 次。

然后我们可以使用相同的查询找到最大数量的航班,然后找到具有该数量的航线,然后进行计数。我怀疑你已经把这部分写下来了,但这只是作为练习。