如何在SQL中的数学运算符中使用别名?

时间:2014-01-26 19:16:10

标签: mysql sql join alias

首先,如果“别名”是错误的词,请纠正我。我正在谈论用AS运算符重命名列。

所以我正在尝试计算这样的平均值:

SELECT
users.username AS player_name,
COUNT(*) AS total_games,
SUM(games.points) AS total_points,
(total_points / total_games) AS average_points

FROM games,
INNER JOIN users
ON games.player_id = users.id
GROUP BY games.player_id

(查询可能有误,只是一个简单的例子)

在此查询中,行

(total_points / total_games) AS average_points

发出错误:unknown column total_points

所以如何解决这个问题以继续使用别名,而不是写这个:

(SUM(games.points) / COUNT(*) ) AS average_points

感谢您的帮助!

3 个答案:

答案 0 :(得分:5)

不幸的是,您不能以这种方式使用列别名。它们仅在处理SELECT语句后才可用。但是,您可以在子查询或公用表表达式(CTE)中执行此操作。这是简单的子查询:

SELECT player_name,
       total_games,
       total_points,
       (total_points / total_games) AS average_points
FROM
 (SELECT
 users.username AS player_name,
 COUNT(*) AS total_games,
 SUM(games.points) AS total_points,

 FROM games,
 INNER JOIN users
 ON games.player_id = users.id
 GROUP BY games.player_id) as InnerQuery

答案 1 :(得分:4)

我很确定不可能使用这样的别名。你将不得不以“长”的方式做到这一点......

(SUM(games.points) / COUNT(*) ) AS average_points

编辑我想将此答案编辑为第二个 @jbeldock 的答案作为我自己多次使用过的解决方案。我发现自己编写公式并在查询的其他部分重用它们,导致复制/粘贴部分出现大乱的查询。将您的forumlas放在子查询中允许您在外部查询中使用其结果并使事情更加优雅。

答案 2 :(得分:0)

您不能在定义的同一级别使用别名 - 您需要将别名定义放在子查询中。但是,您不需要别名,因为SQL具有AVG()函数:

SELECT users.username AS player_name,
       COUNT(*) AS total_games,
       SUM(games.points) AS total_points,
       AVG(games.points) AS average_points
FROM games INNER JOIN
     users
     ON games.player_id = users.id
GROUP BY games.player_id;