9

如何计算别名列上的聚合函数 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 
4

3 回答 3

15

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

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 
于 2013-08-02T15:39:32.467 回答
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带有限制的awhere已经过时了。

于 2013-01-08T15:27:46.813 回答
0

SUM(rank)除非您的分组与您的分组不同,否则这样做没有任何意义COUNT(a.question_id)。否则,SUM 将始终处理一行 - 这是 COUNT 结果的值。此外,您要求在COUNT(a.question_id)哪里指定 GROUP BY 子句也使用a.question_id. 这不会返回您正在寻找的结果。

如果您澄清分组的用途rank,则可以为此进行子查询。

于 2013-01-08T15:25:28.937 回答