1

我有很多板球碗的数据库。架构是:

Player(PlayerID, Initials, Surname)
 - Stores all the players
Bowl(BowlID, Striker, Non-Striker, Bowler, Runs)
 - Stores info for every ball
Team(TeamID, name)
 - Stores all the teams
SquadPlayer(TeamID, PlayerID, MatchID)
 - Stores a record of who was playing at each match and for which team

我试图找出英格兰队中每位球员的六分球数。(我使用的是 openoffice 风格的 HSQL)

SELECT "Player"."Initials", "Player"."Surname", COUNT ("Bowl"."Striker") AS "No. Sixes"
FROM "Bowl", "Player", "Player" AS "Bowler"
WHERE "Bowl"."Striker" = "Player"."PlayerID"
AND "Bowl"."Bowler" = "Bowler"."PlayerID"
AND "Bowl"."Striker" IN (
    SELECT DISTINCT "Player"."PlayerID" 
    FROM "Player", "Team", "SquadPlayer"
    WHERE "Player"."PlayerID" = "SquadPlayer"."PlayerID" 
    AND "Team"."TeamID" = "SquadPlayer"."TeamID" 
    AND "Team"."Name" = 'England' )
AND "Bowl"."Runs" = '6'
GROUP BY "Bowl"."Striker"

这是我试图运行的 SQL,但它不起作用。如果我省略了 SELECT 部分的前两列(Player.Initials 和 Player.Surname),它可以正常工作,但它不是很有用,因为我无法计算出 WHO 的所有六分之一。

我通过java运行它,我得到了异常:

java.sql.SQLException: Not in aggregate function or group by clause

那么为什么这不起作用呢?以及如何在旁边显示名称?

4

4 回答 4

1

当您的 select 子句中有一个计数(或任何聚合函数)时,select-clause 中的所有未聚合列也必须出现在 group-by 子句中。

让你的 group by-clause 看起来像这样:

GROUP BY "Bowl"."Striker", "Player"."Initials", "Player"."Surname"

它应该工作..

于 2012-09-17T14:57:02.307 回答
0

如果您在查询中使用 count、sum 等(聚合函数),则您检索到的所有未在聚合中的列都必须在 group by 子句中。

将您的 group by 子句更改为

GROUP BY  "Player"."Initials", "Player"."Surname"
于 2012-09-17T15:02:48.627 回答
0

子句中的任何字段都SELECT需要带有聚合函数或包含在GROUP BY子句中,这就是您收到此错误的原因。因此,您必须"Player"."Initials", "Player"."Surname"GROUP BY子句中包含 或对它们使用聚合函数。就像是:

SELECT "Player"."Initials", "Player"."Surname", 
      COUNT ("Bowl"."Striker") AS "No. Sixes"
FROM "Bowl", "Player", "Player" AS "Bowler"
WHERE "Bowl"."Striker" = "Player"."PlayerID"
AND "Bowl"."Bowler" = "Bowler"."PlayerID"
AND "Bowl"."Striker" IN (
    SELECT DISTINCT "Player"."PlayerID" 
    FROM "Player", "Team", "SquadPlayer"
    WHERE "Player"."PlayerID" = "SquadPlayer"."PlayerID" 
    AND "Team"."TeamID" = "SquadPlayer"."TeamID" 
    AND "Team"."Name" = 'England' )
AND "Bowl"."Runs" = '6'
GROUP BY "Bowl"."Striker", "Player"."Initials", "Player"."Surname"
于 2012-09-17T14:56:30.490 回答
0

您的分组依据应该是您未汇总的列。

SELECT "Player"."Initials", "Player"."Surname", COUNT ("Bowl"."Striker") AS "No. Sixes"
FROM "Bowl", "Player", "Player" AS "Bowler"
WHERE "Bowl"."Striker" = "Player"."PlayerID"
AND "Bowl"."Bowler" = "Bowler"."PlayerID"
AND "Bowl"."Striker" IN (
    SELECT DISTINCT "Player"."PlayerID" 
    FROM "Player", "Team", "SquadPlayer"
    WHERE "Player"."PlayerID" = "SquadPlayer"."PlayerID" 
    AND "Team"."TeamID" = "SquadPlayer"."TeamID" 
    AND "Team"."Name" = 'England' )
AND "Bowl"."Runs" = '6'
GROUP BY "Player"."Initials", "Player"."Surname"
于 2012-09-17T14:56:33.753 回答