我有一个很多板球碗的数据库。 架构是:
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
那么为什么这不起作用?如何在旁边显示名称?
答案 0 :(得分:1)
如果select子句中有count(或任何聚合函数),则select-clause中的所有未聚合列也必须出现在group-by子句中。
让你的组子句看起来像这样:
GROUP BY "Bowl"."Striker", "Player"."Initials", "Player"."Surname"
它应该有用..
答案 1 :(得分: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"
答案 2 :(得分: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"
答案 3 :(得分:0)
如果在查询中使用count,sum等(聚合函数),则检索到的不在聚合中的所有列都必须在group by子句中。
将您的group by子句更改为
GROUP BY "Player"."Initials", "Player"."Surname"