SQL 查询不会 运行 因为错误分组
SQL query wont run because of a strange group by Error
我使用 PGadmin4 SQL 服务器在 python 界面中编写了这个 SQL 查询。
它应该是 return 一个有序的(按总和降序,如果相等则按 stadiumID 升序),其中总和是在体育场内进球的数量。如果体育场内没有任何比赛,则总和应为 0。
比赛table有所有比赛的记录,比赛发生在哪个体育场,人群中有多少人
体育场table有体育场的数量、容量和拥有它的球队
比分table包含进球所在的比赛、进球的球员以及他进球的数量
数据库:
query = sql.SQL("
SELECT T.Stadiumid AS Stadiumid, T.SUM(Amount) AS Sum
FROM(
(SELECT game.Stadiumid AS Stadiumid,SUM(Amount) AS Sum
FROM game,score
WHERE (game.Matchid=score.Matchid)
)
UNION
(SELECT stadium.Stadiumid AS unplayedStadiumid,0 AS unplayedSum
FROM stadium
WHERE (stadium.Stadiumid NOT IN (SELECT game.Stadiumid FROM game))
)
) AS T
GROUP BY T.Stadiumid
ORDER BY T.Sum DESC,T.Stadiumid
")
执行查询时出现以下错误消息:
column "game.stadiumid" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...d AS Stadiumid, T.SUM(Amount) AS Sum FROM((SELECT game.Stadi...
好像是什么问题?
您在此子查询中错过了分组依据
(SELECT game.Stadiumid AS Stadiumid,SUM(Amount) AS Sum
FROM game,score
WHERE (game.Matchid=score.Matchid)
GROUP BY game.Stadiumid -- missing group by
)
我相信您的第一个内部 select 中缺少 GROUP BY
。在那里,您正在寻找 SUM(Amount)
,但您没有指定应该对哪些变量求和。
如果您想对所有 game.Stadiumid
求和,则此代码适用于您的联盟的第一部分:
SELECT game.Stadiumid AS Stadiumid,SUM(Amount) AS Sum
FROM game,score
WHERE (game.Matchid=score.Matchid)
GROUP BY game.Stadiumid
我使用 PGadmin4 SQL 服务器在 python 界面中编写了这个 SQL 查询。
它应该是 return 一个有序的(按总和降序,如果相等则按 stadiumID 升序),其中总和是在体育场内进球的数量。如果体育场内没有任何比赛,则总和应为 0。
比赛table有所有比赛的记录,比赛发生在哪个体育场,人群中有多少人
体育场table有体育场的数量、容量和拥有它的球队
比分table包含进球所在的比赛、进球的球员以及他进球的数量
数据库:
query = sql.SQL("
SELECT T.Stadiumid AS Stadiumid, T.SUM(Amount) AS Sum
FROM(
(SELECT game.Stadiumid AS Stadiumid,SUM(Amount) AS Sum
FROM game,score
WHERE (game.Matchid=score.Matchid)
)
UNION
(SELECT stadium.Stadiumid AS unplayedStadiumid,0 AS unplayedSum
FROM stadium
WHERE (stadium.Stadiumid NOT IN (SELECT game.Stadiumid FROM game))
)
) AS T
GROUP BY T.Stadiumid
ORDER BY T.Sum DESC,T.Stadiumid
")
执行查询时出现以下错误消息:
column "game.stadiumid" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: ...d AS Stadiumid, T.SUM(Amount) AS Sum FROM((SELECT game.Stadi...
好像是什么问题?
您在此子查询中错过了分组依据
(SELECT game.Stadiumid AS Stadiumid,SUM(Amount) AS Sum
FROM game,score
WHERE (game.Matchid=score.Matchid)
GROUP BY game.Stadiumid -- missing group by
)
我相信您的第一个内部 select 中缺少 GROUP BY
。在那里,您正在寻找 SUM(Amount)
,但您没有指定应该对哪些变量求和。
如果您想对所有 game.Stadiumid
求和,则此代码适用于您的联盟的第一部分:
SELECT game.Stadiumid AS Stadiumid,SUM(Amount) AS Sum
FROM game,score
WHERE (game.Matchid=score.Matchid)
GROUP BY game.Stadiumid