从嵌套查询中选择最大值

时间:2017-11-05 23:18:16

标签: sql db2 greatest-n-per-group

我有一个嵌套查询,它返回按不同乘客类型分组的所有乘客的总费用。

SELECT PASSNGR.type , sum(FARE.fee) AS totalFare 
  FROM Passenger AS PASSNGR 
  JOIN Fare AS FARE ON (PASSNGR.type = FARE.type) 
  GROUP BY PASSNGR.type 
  ORDER BY totalFare DESC

我试图了解如何选择具有Max(totalFare)的行。我环顾四周,但大部分是从定义的表中选择最大值,因为我使用嵌套查询来生成每个乘客类型的totalFare。

我尝试在初始选择之前嵌套另一个Select MAX(totalFare),但是它只返回max的值而不是类型。

SELECT MAX(totalFare) 
  FROM (SELECT PASSNGR.type , sum(FARE.fee) AS totalFare 
          FROM Passenger AS PASSNGR 
          JOIN Fare AS FARE ON (PASSNGR.type = FARE.type) 
          GROUP BY PASSNGR.type ORDER BY totalFare)

1 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

SELECT p.type, sum(f.fee) AS totalFare 
FROM Passenger p JOIN
     Fare f
     ON p.type = f.type
GROUP BY p.type 
ORDER BY totalFare DESC
FETCH FIRST 1 ROW ONLY;

我应该注意JOIN没有必要。你可以做;

SELECT f.type, sum(f.fee) AS totalFare 
FROM Fare f
GROUP BY f.type 
ORDER BY totalFare DESC
FETCH FIRST 1 ROW ONLY;