SQL GET COLUMN1,MAX(AVG)为COLUMN2

时间:2015-03-29 10:31:04

标签: sql sql-server max average

这是我的表:

ID  NAME        FNAME      CITY     SALARY
-----------------------------------------
1   Delicat     Antoine    Paris    21000
2   Rabago      Sylvain    Toulouse 21000
3   Dupont      Patrick    Nice     18000
4   Aristides   Hector     Paris    17000
5   Ramaji      Jordan     Toulouse 19000
6   Droda       Erika      Paris    18000
7   Pernelle    Emilie     Nice     17000
8   Laourd      Raoul      Lyon     15000
9   Alesi       Jean       Nice     18000
10  Straud      Amandine   Paris    20000

我需要显示拥有最高平均工资的城市。 我可以按城市显示AVG:

SELECT CITY, AVG(SALARY) as avg_salary
FROM PILOTE
GROUP BY CITY
CITY     avg_salary
-----------------
Lyon        15000
Nice        17666
Paris       19000
Toulouse    20000

我可以显示最高平均工资:

SELECT MAX(AVG_SALARY) as MAX
FROM (SELECT CITY, AVG(SALARY) as AVG_SALARY
FROM PILOTE
GROUP BY CITY ) as tmp
MAX
------
20000

但我需要显示最高平均工资和城市,我不知道该怎么做。

提前致谢。

1 个答案:

答案 0 :(得分:1)

使用TOP 1Order by一起获取City max平均Salary

SELECT TOP 1 CITY, AVG(SALARY) as AVG_SALARY
FROM PILOTE
GROUP BY CITY
ORDER BY AVG_SALARY DESC

或使用Row_number窗口函数

select CITY,AVG_SALARY
(
SELECT Row_number()over(order by AVG(SALARY) Desc) as RN,CITY, AVG(SALARY) as avg_salary
FROM PILOTE
GROUP BY CITY
) A
Where RN =1