如何计算别名列上的聚合函数SUM?

时间:2013-01-08 15:07:24

标签: mysql sql

如何在别名列上计算聚合函数SUM?

SELECT a.question_id, 
       a.level, 
       Count(a.question_id) AS rank, 
       Sum(rank)        AS total 
FROM   logs AS a, 
       question AS b 
WHERE  a.question_id = b.q_id 
       AND a.level = '2' 
GROUP  BY a.question_id 
ORDER  BY rank DESC 

3 个答案:

答案 0 :(得分:12)

只需使用(SELECT别名)包装重用的别名:

SELECT a.question_id, 
       a.level, 
       COUNT(a.question_id) AS rank, 
       SUM(SELECT(rank)) AS total 
FROM   logs AS a, 
       question AS b 
WHERE  a.question_id = b.q_id 
       AND a.level = '2' 
GROUP  BY a.question_id 
ORDER  BY rank DESC 

答案 1 :(得分:5)

SQL的范围规则不允许您在同一select中使用别名。虽然这似乎是不合理的,但它可以防止诸如此类的混淆:

select 2*x as x, x+1

第二个变量引用哪个x

您可以使用子查询来解决此问题:

select t.*, Sum(rank) AS total 
from (SELECT a.question_id, a.level, Count(a.question_id) AS rank, 
      FROM logs AS a join
           question AS b 
           on a.question_id = b.q_id 
      WHERE a.level = '2' 
      GROUP  BY a.question_id 
     ) t
ORDER BY rank DESC

我还修复了你的连接语法。使用逗号表示在cross join子句中有where限制的{{1}}已经过时了。

答案 2 :(得分:0)

除非SUM(rank)的分组与COUNT(a.question_id)的分组不同,否则执行此操作并不合理。否则,SUM将始终在一行上工作 - 这是COUNT结果的值。此外,您要求COUNT(a.question_id)指定GROUP BY子句以使用a.question_id。这不会返回您要查找的结果。

如果您澄清了rank的分组内容,可以为此制作一个子查询。