在 SQL 语句中除以零如何避免特定记录 returns 除以零
Division by zero in SQL statement how to avoid specific record if it returns division by zero
我想发表一个声明,将球员的进球数除以比赛场数。
如果玩家玩了 0 场比赛,将发生 0 分。我如何“跳过”或忽略它并显示 N/A 而不是每场比赛的进球数?
这是我目前拥有的:
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored, ROUND(GoalsScored/GamesPlayed ,2) AS GoalsPerGame
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
ORDER BY GoalsScored DESC
我在 delphi 10.3 中这样做,所以表的连接是在 where 语句中完成的,但这不会影响一般问题。
如果我为一张唱片做这件事,我会做的
if tblStatistics['GamesPlayed'] = 0 then
begin
qryStatsStatic.SQL.Clear;
qryStatsStatic.SQL.Add('
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored, "N/A" AS GoalsPerGame
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
ORDER BY GoalsScored DESC');
qryStatistics.open;
end;
但我的问题是多条记录。
SQL 具有 CASE 语句,该语句仅在找到匹配项之前执行。
CASE WHEN COALESCE(GamesPlayed,0) = 0 THEN 0
ELSE ROUND(GoalsScored/GamesPlayed,2)
END AS GoalsPerGame
每场比赛的进球数也是 goals/games。
您可以使用大多数流行的 DBMS 中都存在的简短 nullif
函数:
select
...,
ROUND(GamesPlayed/nullif(GoalsScored, 0) ,2) as GoalsPerGame
...
尝试 SQL 联盟:
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored,
ROUND(GamesPlayed/GoalsScored ,2) AS GoalsPerGame
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
AND GoalsScored <> 0
UNION
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored, 0
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
AND GoalsScored = 0
ORDER BY GoalsScored DESC
我想发表一个声明,将球员的进球数除以比赛场数。 如果玩家玩了 0 场比赛,将发生 0 分。我如何“跳过”或忽略它并显示 N/A 而不是每场比赛的进球数? 这是我目前拥有的:
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored, ROUND(GoalsScored/GamesPlayed ,2) AS GoalsPerGame
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
ORDER BY GoalsScored DESC
我在 delphi 10.3 中这样做,所以表的连接是在 where 语句中完成的,但这不会影响一般问题。 如果我为一张唱片做这件事,我会做的
if tblStatistics['GamesPlayed'] = 0 then
begin
qryStatsStatic.SQL.Clear;
qryStatsStatic.SQL.Add('
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored, "N/A" AS GoalsPerGame
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
ORDER BY GoalsScored DESC');
qryStatistics.open;
end;
但我的问题是多条记录。
SQL 具有 CASE 语句,该语句仅在找到匹配项之前执行。
CASE WHEN COALESCE(GamesPlayed,0) = 0 THEN 0
ELSE ROUND(GoalsScored/GamesPlayed,2)
END AS GoalsPerGame
每场比赛的进球数也是 goals/games。
您可以使用大多数流行的 DBMS 中都存在的简短 nullif
函数:
select
...,
ROUND(GamesPlayed/nullif(GoalsScored, 0) ,2) as GoalsPerGame
...
尝试 SQL 联盟:
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored,
ROUND(GamesPlayed/GoalsScored ,2) AS GoalsPerGame
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
AND GoalsScored <> 0
UNION
SELECT PlayerName, PlayerSurname, GamesPlayed, GoalsScored, 0
FROM tblPlayers , tblStatistics
WHERE tblPlayers.PlayerID = tblStatistics.PlayerID
AND GoalsScored = 0
ORDER BY GoalsScored DESC