我正在尝试根据他们在主场和客场的时间来计算每支球队的得分和进球数之间的净胜球。但问题是我收到了这个错误:
无法对包含聚合或子查询的表达式执行聚合函数。
我注释掉了“Goal_Difference”代码,想知道导致此问题的原因并且可以修复。谢谢
ALTER VIEW League_Table
AS
SELECT SUM(
CASE
WHEN t.TeamID = f.HomeTeamID THEN f.HomeScore
-- Home Fixture
WHEN t.TeamID = f.AwayTeamID THEN f.AwayScore
-- Away Fixture
END
) AS Goals_Scored,
SUM(
CASE
WHEN t.TeamID = f.HomeTeamID THEN f.AwayScore
-- Home Fixture
WHEN t.TeamID = f.AwayTeamID THEN HomeScore
-- Away Fixture
END
) AS Goals_Against
-- SUM(
-- CASE
-- WHEN t.TeamID = f.HomeTeamID THEN
-- CASE
-- WHEN f.HomeScore IS NOT NULL THEN SUM(f.HomeScore) - SUM(f.AwayScore)
-- -- Home Fixture
-- END
-- WHEN t.TeamID = f.AwayTeamID THEN
-- CASE
-- WHEN f.AwayScore IS NOT NULL THEN SUM(f.AwayScore) - SUM(f.HomeScore)
-- -- Away Fixture
-- END
-- END
--) AS Goal_Difference
FROM dbo.Team t
--Season TBC
INNER JOIN dbo.Fixture f ON t.TeamID IN (f.HomeTeamID, f.AwayTeamID)
GROUP BY t.TeamName
GO
SELECT *
FROM League_Table lt
ORDER BY Points DESC--, Goal_Difference;
答案 0 :(得分:1)
将Goal_Difference
更改为:
SUM(
CASE
WHEN t.TeamID = f.HomeTeamID THEN
CASE
WHEN f.HomeScore IS NOT NULL THEN f.HomeScore - f.AwayScore
-- Home Fixture
END
WHEN t.TeamID = f.AwayTeamID THEN
CASE
WHEN f.AwayScore IS NOT NULL THEN f.AwayScore - f.HomeScore
-- Away Fixture
END
END
) AS Goal_Difference
如果您在CASE
之前汇总,则无法在WHEN
中再次汇总,而sum(sum(..
变为print
,这是不允许的。我认为这不是你想要的,所以我只是删除了内部总和。