我有一个小问题。我正在使用这样的查询:
SELECT SUM(...) AS result1, SUM(...) AS result2 FROM ...
我的问题是如何在表达式中使用result1和result2,如下所示:
SELECT SUM(...) AS result1, SUM(...) AS result2, result1*100/result2 AS percentage FROM ...
有没有办法只使用SUM()
函数或其他函数的结果?
我已尝试过如上所述,但这会返回错误。
答案 0 :(得分:2)
有两种方法要么你需要重复整个表达式,要么使用subselect
SELECT SUM(first_col) AS result1, SUM(second_col) AS result2
SUM(first_col) * 100 /SUM(second_col) percentage
FROM ...
或子选择
SELECT result1, result2 , result1*100/result2 AS percentage
FROM (
SELECT SUM(first_col) AS result1, SUM(second_col) AS result2
FROM ...
) t
答案 1 :(得分:1)
您可以使用子查询,也可以重复表达式:
SELECT SUM(...) AS result1,
SUM(...) AS result2,
SUM(...)*100/SUM(...) AS percentage
FROM ...
SQL不允许您在查询的同一级别引用列别名。
答案 2 :(得分:1)
最简单的方法是再次使用SUM(),
所以它会是:
SELECT
SUM(var1) AS result1,
SUM(var2) AS result2,
(SUM(var1)*100/SUM(var2)) AS percentage
FROM ...
MySQL / SQL到目前为止还没有允许您使用自定义列,它们必须在数据库中定义列。