选择具有最大值的行

时间:2015-07-09 21:11:26

标签: sql ms-access greatest-n-per-group

我有一个名为qryA380的MS Access查询,它使用多个INNER JOIN来加入几个表。 运行查询将显示如下结果:

+----+-----------+----------+------------+
| ID |  Aircraft | Route.ID | Passengers |
+----+-----------+----------+------------+
| 23 |   A-380   |    1     |     556    |
|  2 |   A-380   |    2     |     652    |
| 54 |   A-380   |    2     |     489    |
| 16 |   A-380   |    1     |     598    |
| 39 |   A-380   |    1     |     627    |
| 45 |   A-380   |    3     |     392    |
| 74 |   A-380   |    3     |     726    |
+----+-----------+----------+------------+

我的计划是选择最小的Route.ID(在这种情况下它是1),最终结果应为:

+----+-----------+----------+------------+
| ID |  Aircraft | MinRoute | Passengers |
+----+-----------+----------+------------+
| 23 |   A-380   |    1     |     556    |
| 16 |   A-380   |    1     |     598    |
| 39 |   A-380   |    1     |     627    |
+----+-----------+----------+------------+

我认为这将是直截了当的简单。为了节省时间,我创建了第二个查询来完成这项工作:

SELECT [qryA380].ID, [qryA380].Aircraft, MIN([qryA380].Route.ID) AS MinRoute, [qryA380].Passengers
FROM [qryA380]
GROUP BY [qryA380].ID, [qryA380].Aircraft, [qryA380].Passengers

但是我不断得到一张与qryA380生成的表格相同的表格。它在结果中包含所有Route.ID

2 个答案:

答案 0 :(得分:0)

应排除Passenger和ID列,因为它们具有唯一值。通过使用子查询,我现在能够生成所需的结果:

SELECT [qryA380].*
FROM (
  SELECT MIN([qryA380].Route.ID) AS MinRoute
  FROM [qryA380]
) tblMinRoute
INNER JOIN [qryA380]
ON [qryA380].Route.ID = tblMinRoute.MinRoute

答案 1 :(得分:0)

试试这个

   SELECT [qryA380].*
    FROM [qryA380]
    WHERE [qryA380].Route.ID = (
            SELECT min(Route.ID)
            FROM [qryA380]
            )