I have a sub-select within a larger query and I'm trying to add a calculated field to the sub-select using a CASE statement.
My sub-select looks like this:
LEFT JOIN
(
SELECT Course_ID, Question_ID, Answer, (HIP =
CASE
WHEN Question_ID = 77 THEN "1"
WHEN Question_ID = 78 THEN "2"
WHEN Question_ID = 79 THEN "3"
WHEN Question_ID = 80 THEN "4"
WHEN Question_ID = 81 THEN "5"
WHEN Question_ID = 82 THEN "6"
ELSE "Undefined HIP"
END)
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
) ercehip
ON course.Course_ID = ercehip.Course_ID
When I try to access ercehip.HIP in my parent select statement though, it says it is undefined. Any ideas on how to solve this? Thanks
HIP = (..)
, you will need to use Aliasing instead. CASE .. WHEN()
are checking against Question_ID
only, you can move it to besides Case
clause, and make the query less verbose. Try the following instead:
(
SELECT Course_ID, Question_ID, Answer,
(CASE Question_ID
WHEN 77 THEN "1"
WHEN 78 THEN "2"
WHEN 79 THEN "3"
WHEN 80 THEN "4"
WHEN 81 THEN "5"
WHEN 82 THEN "6"
ELSE "Undefined HIP"
END) AS HIP
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
) AS ercehip
You must determinate alias of the calculated field as MySQL syntax require
SELECT Course_ID, Question_ID, Answer, (
CASE
WHEN Question_ID = 77 THEN "1"
WHEN Question_ID = 78 THEN "2"
WHEN Question_ID = 79 THEN "3"
WHEN Question_ID = 80 THEN "4"
WHEN Question_ID = 81 THEN "5"
WHEN Question_ID = 82 THEN "6"
ELSE "Undefined HIP"
END) as HIP
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
OR
SELECT Course_ID, Question_ID, Answer, (
CASE
WHEN Question_ID = 77 THEN "1"
WHEN Question_ID = 78 THEN "2"
WHEN Question_ID = 79 THEN "3"
WHEN Question_ID = 80 THEN "4"
WHEN Question_ID = 81 THEN "5"
WHEN Question_ID = 82 THEN "6"
ELSE "Undefined HIP"
END) HIP
FROM proposals.new_gen_ed_answers
WHERE Answer = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.