GROUP BY学习Derby SQL的麻烦

时间:2012-03-13 20:51:58

标签: sql derby

我已经形成了这个查询来从每个获胜最多的队伍中产生投手。我的麻烦来自于我需要以某种方式对它们进行分组,并且在尝试这样做时我一直存在范围问题。 W是每个投手的胜利数。这是我预先分组的陈述......

SELECT 
    (SELECT p1.nameFirst FROM Players p1 Where (one.playerID = p1.playerID)), 
    (SELECT p1.nameLast FROM Players p1 Where (one.playerID = p1.playerID)), 
    one.W, (SELECT t1.name FROM Teams t1 Where(one.teamID = t1.teamID)) 
 FROM Pitching one
 Where (one.W >= ALL
    (SELECT two.W
    FROM Pitching two
    Where (two.teamID = one.teamID)));

我需要按照联盟和联赛组内的分组对元组进行分组。团队表中存在联盟(lgID)和分部(divID)。有人能指出我正确的方向吗?谢谢。

这是目前输出的前六行......

Zach    Britton         11  Baltimore Orioles
Mark    Buehrle         13  Chicago White Sox
Madison Bumgarner       13    San Francisco Giants
Jhoulys Chacin          11  Colorado Rockies
Bruce   Chen            12  Kansas City Royals
Kevin   Correia         12  Pittsburgh Pirates

我想要的输出是按照联赛(NL / AL)对这些球队进行排序,并且在联赛内按分区排序。

2 个答案:

答案 0 :(得分:1)

根据您更新的评论。我想这就是你想要的。

SELECT
   pl.nameFirst
   , pl.nameLast
   , p.W
   , t.name
FROM
(
    SELECT
        MAX(p1.W) AS W
        , p1.teamId
    FROM
    Pitching p1
    GROUP BY
        p1.teamId
) t1
JOIN
    Pitching p
       ON t1.W = p.W
       AND t1.teamId = p.teamId
JOIN
   Players pl
     ON p.playerID = pl.playerID
JOIN
   Teams t
     ON p.teamID = t.teamID
ORDER BY
   t.lgID
   , t.divID

我同意swasheck,你的架构有一些改进的机会。正如swascheck所说,teamId应该是玩家。不是在投球。

答案 1 :(得分:1)

这可能是结构问题。使用我认为是你的结构,我们可以像这样缩小它:

 select Players.nameFirst, Players.nameLast, TopPitcher.Winner, 
  Teams.name, League.Name, Division.Name
    from    (select playerID, max(Wins) as Winner
    from (select playerID, teamID, count(W) as Wins
        from Pitching
        group by playerID, teamID ) PitchingWins) TopPitcher       
    join Players 
    on TopPitcher.playerID = Players.playerID 
    join Teams 
    on Teams.teamID = Players.teamID
    join League 
    on Teams.leagueID = League.leagueID
    join Division 
    on League.divisionID = Division.divisionID
    order by League.Name, Division.Name

现在。话虽如此,这仅适用于您给出的结构(使用其他插值)。你的整体结构有问题,因为我可能会将球员与球队联系起来而不是投球到球队,因为你可能会因球队胜利和投手获胜而获得某种数据错误。