从table1中选择TOP列,将table2与其名称连接起来

时间:2016-05-06 19:12:36

标签: sql sql-server

我有一个包含这两列的TABLE1,存储来自航班的出发和到达标识符:

dep_id  arr_id

   1    2
   6    2
   6    2
   6    2
   6    2
   3    2
   3    2
   3    2
   3    4
   3    4
   3    6
   3    6

和TABLE2,其中各自的ID包含其ICAO代码:

id  icao
1   LPPT
2   LPFR
3   LPMA
4   LPPR
5   LLGB
6   LEPA
7   LEMD

如何选择TABLE1的最高计数(最常用的出发ID和最常用的到达ID)并将其与TABLE2中的相应ICAO代码分组,以便我可以从提供的示例数据中获取:

most_arrivals   most_departures
    LPFR             LPMA

获取其中一个很简单,但无论我尝试什么,混合两个或更多列对我来说似乎都不适用。

2 个答案:

答案 0 :(得分:1)

你可以这样做。

创建并填充表格。

CREATE TABLE dbo.Icao
(
    id int NOT NULL PRIMARY KEY,
    icao nchar(4) NOT NULL
);

CREATE TABLE dbo.Flight
(
    dep_id int NOT NULL
        FOREIGN KEY REFERENCES dbo.Icao(id),
    arr_id int NOT NULL
        FOREIGN KEY REFERENCES dbo.Icao(id)
);

INSERT INTO dbo.Icao (id, icao)
    VALUES
    (1, N'LPPT'),
    (2, N'LPFR'),
    (3, N'LPMA'),
    (4, N'LPPR'),
    (5, N'LLGB'),
    (6, N'LEPA'),
    (7, N'LEMD');

INSERT INTO dbo.Flight (dep_id, arr_id)
    VALUES
    (1, 2),
    (6, 2),
    (6, 2),
    (6, 2),
    (6, 2),
    (3, 2),
    (3, 2),
    (3, 2),
    (3, 4),
    (3, 4),
    (3, 6),
    (3, 6);

然后使用两个子查询进行SELECT。

SELECT
    (SELECT TOP 1 I.icao
        FROM dbo.Flight AS F
            INNER JOIN dbo.Icao AS I
                ON I.id = F.arr_id
        GROUP BY I.icao
        ORDER BY COUNT(*) DESC) AS 'most_arrivals',
    (SELECT TOP 1 I.icao
        FROM dbo.Flight AS F
            INNER JOIN dbo.Icao AS I
                ON I.id = F.dep_id
        GROUP BY I.icao
        ORDER BY COUNT(*) DESC) AS 'most_departures';

enter image description here

执行查询时,单击工具栏上的此按钮以包含实际执行计划。

enter image description here

这是查询的图形执行计划。每个图标表示将由SQL Server引擎执行的操作。箭头表示数据流。流向是从右到左,因此结果是最左边的图标。

enter image description here

答案 1 :(得分:0)

试试这个:

select
    (select name
        from table2 where id = (
        select top 1 arr_id
        from table1
        group by arr_id
        order by count(*) desc)
    )  as most_arrivals,
    (select name
        from table2 where id = (
        select top 1 dep_id
        from table1
        group by dep_id
        order by count(*) desc)
    ) as most_departures