9

How to calculate aggregate function SUM on an alias column?

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
  • You could use a sub-query. Good luck! Commented Jan 8, 2013 at 15:09
  • 1
    SUM(COUNT(a.step_id)) AS total. Aliases are only available in GROUP BY, ORDER BY or HAVING (aside from direct output). Commented Jan 8, 2013 at 15:14
  • please give me example.. ;) Commented Jan 8, 2013 at 15:24
  • 1
    You are declaring GROUP BY a.question_id and also COUNT() and SUM() on the same field? Commented Jan 8, 2013 at 15:29

3 Answers 3

14

Simply wrap your reused alias with (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 
Sign up to request clarification or add additional context in comments.

3 Comments

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT(...)) AS ... at line_1'
i am not sure why this answer is accepted and so many upvotes. its giving error syntax error
Maybe because this answer is almost 7 years old, and you may have a recent MySQL version.
6

The scoping rules of SQL do not allow you to use an alias in the same select. Although this seems unreasonable, it is to prevent confusions such as:

select 2*x as x, x+1

Which x does the second variable refer to?

You can solve this problem by using a subquery:

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

I also fixed your join syntax. The use of a comma to mean a cross join with restrictions in the where clause is rather outdated.

Comments

0

It doesn't really make sense to do this unless you have a different grouping for SUM(rank) than you would for COUNT(a.question_id). Otherwise, the SUM will always be working on one row - which is the value of the result of COUNT. Moreover, you are asking for COUNT(a.question_id) where you have specified the GROUP BY clause to also use a.question_id. This is not going to return the results you are looking for.

If you clarify what your grouping would be for rank, a subquery could be made for this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.