如何从不同的组中选择最高计数属性?

时间:2018-06-02 19:28:43

标签: sql oracle plsql

所以我有一张桌子上有球员数据(名字,球队等等)和一张有进球的球员(得分球员,本地球队等......)。我需要做的是,从每支球队获得最高分。所以我得到的结果是:

  • 德国 - 无论名称 - 1

  • 德国 - 另一个家伙 - 5

  • 西班牙 - 另一个名字 - 8
  • 意大利 - 另一个名字 - 6

正如你可以看到球队重复,我希望他们不重复,只是获得每支球队的最高得分手。

现在我有这个:

SELECT  P.TEAM_PLAYER, G.PLAYER_GOAL, COUNT(*) AS "TOTAL GOALS" FROM PLAYER P, GOAL G
WHERE TO_CHAR(G.DATE_GOAL, 'YYYY')=2002
AND P.NAME = G.PLAYER_GOAL
GROUP BY G.PLAYER_GOAL, P.TEAM_PLAYER
HAVING COUNT(*)>=ALL (SELECT COUNT(*) FROM PLAYER P2 where P.TEAM_PLAYER = P2.TEAM_PLAYER GROUP BY P2.TEAM_PLAYER)
ORDER BY COUNT(*) DESC;

我100%肯定我已经接近了,而且我非常确定我必须使用HAVING功能做到这一点,但我无法做到这一点。

如果没有HAVING,它会返回所有球员,他们的球队以及他们进球数目的列表,现在我想将其减少到每个球队只有一名球员。

PD:GOAL表中的团队是本地和访问团队,所以我必须使用Player表来获得团队。此外,目标表不是球员名单和他们有多少进球数,而是每个目标和进球得分的名单。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以尝试此查询。

只获取MAX列的PLAYER_GOALSUM(G.PLAYER_GOAL)代替COUNT(*)

SELECT  P.TEAM_PLAYER, 
        MAX(G.PLAYER_GOAL) "PLAYER_GOAL", 
        SUM(G.PLAYER_GOAL) AS "TOTAL GOALS" 
FROM PLAYER P 
INNER JOIN GOAL G 
ON P.NAME = G.PLAYER_NAME
WHERE TO_CHAR(G.DATE_GOAL, 'YYYY')=2002
GROUP BY P.TEAM_PLAYER
ORDER BY SUM(G.PLAYER_GOAL) DESC;

注意:

  • 避免使用逗号到join表,这是旧的join样式,您可以使用内部联接。

修改

我不知道您的表架构,但此查询可能有效。

使用子查询来包含当前结果集。然后获取MAX函数和GROUP BY

SELECT T.TEAM_PLAYER,
            T.PLAYER_GOAL,
            MAX(TOTAL_GOALS) AS "TOTAL GOALS"
FROM 
(
    SELECT  P.TEAM_PLAYER, G.PLAYER_GOAL, COUNT(*) AS "TOTAL_GOALS" FROM 
    PLAYER P, GOAL G
    WHERE TO_CHAR(G.DATE_GOAL, 'YYYY')=2002
    AND P.NAME = G.PLAYER_GOAL
    GROUP BY G.PLAYER_GOAL, P.TEAM_PLAYER
    HAVING COUNT(*)>=ALL (SELECT COUNT(*) FROM PLAYER P2 where P.TEAM_PLAYER = P2.TEAM_PLAYER GROUP BY P2.TEAM_PLAYER)
) T
GROUP BY T.TEAM_PLAYER,
         T.PLAYER_GOAL
ORDER BY MAX(TOTAL_GOALS) DESC