从一个SUM()中找到MAX()。

huangapple go评论59阅读模式
英文:

Finding MAX() from a SUM()

问题

我需要获取飞行里程最多的乘客。

SELECT TP.strFirstName, 
    TP.strLastName, 
    SUM(TF.intMilesFlown) AS TotalMilesFlown
FROM TPassengers AS TP
JOIN TFlightPassengers AS TFP
     ON TP.intPassengerID = TFP.intPassengerID
JOIN TFlights AS TF
     ON TFP.intFlightID = TF.intFlightID		  
GROUP BY TP.strLastName, 
    TP.strFirstName
ORDER BY TotalMilesFlown DESC
LIMIT 1;
英文:

I need to get the passenger with the most miles flown.

SELECT TP.strFirstName, 
    TP.strLastName, 
    sum(TF.intMilesFlown)
FROM TPassengers AS TP
JOIN TFlightPassengers AS TFP
     ON TP.intPassengerID = TFP.intPassengerID
JOIN TFlights AS TF
     ON TFP.intFlightID = TF.intFlightID		  
GROUP BY TP.strLastName, 
    TP.strFirstName

So this finds my sum but I don't know how to find the sum's max. I know it probably takes some subquery.

答案1

得分: 2

你可以使用 TOP 1ORDER BY..DESC 来获取最大的行。

SELECT TOP 1 TP.strFirstName, 
    TP.strLastName, 
    sum(TF.intMilesFlown)
FROM TPassengers AS TP
JOIN TFlightPassengers AS TFP
     ON TP.intPassengerID = TFP.intPassengerID
JOIN TFlights AS TF
     ON TFP.intFlightID = TF.intFlightID          
GROUP BY TP.strLastName, 
    TP.strFirstName
ORDER BY SUM(TF.intMilesFlown) DESC;
英文:

You can use TOP 1 with an ORDER BY..DESC to get the max row.

SELECT TOP 1 TP.strFirstName, 
    TP.strLastName, 
    sum(TF.intMilesFlown)
FROM TPassengers AS TP
JOIN TFlightPassengers AS TFP
     ON TP.intPassengerID = TFP.intPassengerID
JOIN TFlights AS TF
     ON TFP.intFlightID = TF.intFlightID          
GROUP BY TP.strLastName, 
    TP.strFirstName
ORDER BY SUM(TF.intMilesFlown) DESC;

huangapple
  • 本文由 发表于 2023年5月28日 08:27:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定