2

I have one problem with this query; I can't seem to get ((total + rec_host) / 2) AS total2 to work. How would I go about this procedure without doing:

((((rank_ur + rank_scs + rank_tsk + rank_csb + rank_vfm + rank_orr) / 6) + rec_host ) / 2)

Here's my Query:

   SELECT host_name, 
       SUM(rank_ur) AS cnt1, 
       SUM(rank_scs) AS cnt2,
       SUM(rank_tsk) AS cnt3,
       SUM(rank_csb) AS cnt4,
       SUM(rank_vfm) AS cnt5,
       SUM(rank_orr) AS cnt6,
       SUM(IF(rec_host = 1,1,0)) AS rh1,
       SUM(IF(rec_host = 0,1,0)) AS rh2,
       ((rank_ur + rank_scs + rank_tsk + rank_csb + rank_vfm + rank_orr) / 6) AS total,
       ((total + rec_host) / 2) AS total2
   FROM lhr_reviews 
   GROUP BY host_name
   ORDER BY total 
   DESC LIMIT 0,10
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Justin
  • 75
  • 7

2 Answers2

5

Use a subquery like so:

SELECT 
  host_name, 
  cnt1, 
  cnt2,
  cnt3,
  cnt4,
  cnt5,
  cnt6,
  rh1,
  rh2,
  total,
  ((total + rec_host) / 2) AS total2
FROM
(
   SELECT host_name, 
       rec_host,
       SUM(rank_ur) AS cnt1, 
       SUM(rank_scs) AS cnt2,
       SUM(rank_tsk) AS cnt3,
       SUM(rank_csb) AS cnt4,
       SUM(rank_vfm) AS cnt5,
       SUM(rank_orr) AS cnt6,
       SUM(IF(rec_host = 1,1,0)) AS rh1,
       SUM(IF(rec_host = 0,1,0)) AS rh2,
       ((rank_ur + rank_scs + rank_tsk + 
         rank_csb + rank_vfm + rank_orr
         ) / 6) AS total
   FROM lhr_reviews 
   GROUP BY host_name, rec_host
) t 
ORDER BY total 
DESC LIMIT 0,10;
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
3

What you could do is this:

select x.*, ((x.total + rec_host) / 2) AS total2
from (

SELECT host_name, rec_host,
       SUM(rank_ur) AS cnt1, 
       SUM(rank_scs) AS cnt2,
       SUM(rank_tsk) AS cnt3,
       SUM(rank_csb) AS cnt4,
       SUM(rank_vfm) AS cnt5,
       SUM(rank_orr) AS cnt6,
       SUM(IF(rec_host = 1,1,0)) AS rh1,
       SUM(IF(rec_host = 0,1,0)) AS rh2,
       ((rank_ur + rank_scs + rank_tsk + rank_csb + rank_vfm + rank_orr) / 6) AS total
   FROM lhr_reviews 
   GROUP BY host_name
   ORDER BY total 
   DESC LIMIT 0,10
) as x
;

You cannot use the column as an alias when the alias and other column are in the same level of SELECT. So you can use a derived query which lets you basically rename your columns and/or name any computed columns.Check on Rubens Farias and Rob Van Dam answer here

PS: will search for a better article to update the answer :)

Community
  • 1
  • 1
bonCodigo
  • 14,268
  • 1
  • 48
  • 91