2

我对这个查询有一个问题;我似乎无法((total + rec_host) / 2) AS total2上班。如果不这样做,我将如何执行此程序:

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

这是我的查询:

   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
4

2 回答 2

5

像这样使用子查询:

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;
于 2012-12-11T08:25:12.613 回答
3

你可以做的是:

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
;

当别名与其他列处于同一级别时,不能将该列用作别名SELECT。因此,您可以使用派生查询,它可以让您基本上重命名列和/或命名任何计算列。在这里查看 Rubens Farias 和 Rob Van Dam 的答案

PS:将搜索更好的文章来更新答案:)

于 2012-12-11T08:30:35.363 回答