SQL MAx函数有多个列显示在顶点?

时间:2016-12-05 21:14:23

标签: sql oracle-apex

image1 image2我正在尝试编写一个sql函数来显示我们数据库中每年ppg最高的玩家的年份,玩家名称和ppg。

我们有一个包含所有统计数据的玩家表,以及一个团队表,其中包含与每个赛季相关联的统计数据作为团队总数。

我想做的是从每个赛季中获得最高得分者:

2010: Jake 10ppg
2011: Jake 12 ppg
2012 Carl 13 ppq

这是我当前的查询

SELECT Year, PlayerName, MAX(PPG) AS PPG
FROM PLAYERS_T, TEAM_T
GROUP BY Year
ORDER BY PPG;

然而,这不起作用,我需要做些什么来完成这项工作?

2 个答案:

答案 0 :(得分:0)

这应该有效,但如果PPG相同则显示重复记录。 不知道Team table的用途是什么

<强> SQL DEMO

WITH PLAYERS_T as (
     SELECT 2010 "Year",  'Jake' "PlayerName", 10 ppg     
     UNION 
     SELECT 2011 "Year",  'Jake' "PlayerName", 12 ppg     
     UNION 
     SELECT 2012 "Year",  'Carl' "PlayerName", 13 ppg     
)
 SELECT T1."Year", T1."PlayerName", T1.PPG
 FROM PLAYERS_T T1
 LEFT JOIN PLAYERS_T T2
   ON T1."Year" = T2."Year"
  AND T1.PPG <  T2.PPG
 WHERE T2."Year" IS NULL

输出

enter image description here

答案 1 :(得分:0)

试试这个:

SELECT players_T.playername, players_T.ppg, players_T.year
FROM
(SELECT year, MAX(PPG) AS mx
 FROM players_T
 GROUP BY year) sub
INNER JOIN players_T ON sub.mx = players_T.ppg
WHERE sub.year = players_T.year
ORDER BY players_T.year

在子查询中,每年查找最大ppg。然后我们加入ppg上的球员表来找到球员的名字。结果应该是玩家名称,ppg和年份。让我知道你找到了什么!

编辑:需要包含年份的WHERE子句