我有一个查询在这里我得到一个错误,别名说未知列,这是错误的。我需要得到16_judge_61,16_judge_62,16_judge_63
的总和SELECT s.contestant_number, c.contestant_name, j.judge_name,
SUM(CASE WHEN s.crit_id =17 AND s.judge_id = '61' THEN score END ) AS 16_judge_61,
SUM(CASE WHEN s.crit_id =17 AND s.judge_id = '62' THEN score END ) AS 16_judge_62,
SUM(CASE WHEN s.crit_id =17 AND s.judge_id = '63' THEN score END ) AS 16_judge_63,
(16_judge_61 + 16_judge_62 + 16_judge_63) as total //<--here is the problem
//<--i also tried (sum(16_judge_61) + sum(16_judge_62) + sum(16_judge_63))as total not working as well
FROM tbl_score s INNER JOIN tbl_contestant c ON s.contestant_number = c.contestant_number
INNER JOIN tbl_judges j ON j.judge_id = s.judge_id
WHERE c.gender = 'male'
AND c.con_id = s.con_id
AND j.judge_id =62
GROUP BY s.contestant_number
答案 0 :(得分:2)
您的错误是由于尝试在定义它的同一SELECT
子句中使用别名而引起的。你不能这样做,因为尚未计算别名。
对此问题的膝跳反应只是将CASE
,16_judge_61
和16_judge_62
的三个16_judge_63
语句加在一起。但是,您可以通过识别使用CASE
对三个WHERE IN
值将这三个条件合并为一个judge_id
语句来改进这一点。
尝试此查询:
SELECT s.contestant_number,
c.contestant_name,
j.judge_name,
SUM(CASE WHEN s.crit_id = 17 AND s.judge_id IN (61,62,63)
THEN score END ) AS total
FROM ...
答案 1 :(得分:0)
不确定您使用SUM(CASE ...)
的原因SELECT s.contestant_number, c.contestant_name, j.judge_name,
CASE WHEN s.crit_id =17 AND s.judge_id = '61' THEN score END AS 16_judge_61,
CASE WHEN s.crit_id =17 AND s.judge_id = '62' THEN score END AS 16_judge_62,
CASE WHEN s.crit_id =17 AND s.judge_id = '63' THEN score END AS 16_judge_63,
SUM(16_judge_61 + 16_judge_62 + 16_judge_63) as total
FROM tbl_score s INNER JOIN tbl_contestant c ON s.contestant_number = c.contestant_number
INNER JOIN tbl_judges j ON j.judge_id = s.judge_id
WHERE c.gender = 'male'
AND c.con_id = s.con_id
AND j.judge_id =62
GROUP BY s.contestant_number
答案 2 :(得分:0)
您可以使用子查询,如下所示:
SELECT *, (16_judge_61+16_judge_62+16_judge_63) AS total FROM (
-------------Your wholequery----------------
) t