SQL Case语句错误地替换值

时间:2013-07-09 03:58:52

标签: sql syntax

我正在尝试重命名我具有READ-ONLY访问权限的数据库的一列的值。我还想将两个值组合成一个。我正在使用SQL CASE查询,但它正在错误地转换值。这是我的SQL:

SELECT
DATE(appraisal.created_time),
appraisal_steps.title,
Count(appraisal.appraisal_id),
case appraisal_steps.title
 when "archive" then "A_Archived"
 when "on_sale" then "J_Selling"
 when "under_evaluation" then "F_Evaluating"
 when "evaluated" then "H_Appraisal Complete"
 when "pending" then "B_Pending"
 when "crap" then "C_Not For Lofty"
 when "waiting_internal_expert_evaluation" then "D_Unclaimed"
 when ("expert_needs_information" OR "admin_needs_information") then "E_Waiting"
 when "seller_answered_to_expert_question" then "G_Needs_Attn"
 when "ready_to_be_sold" then "I_Ready"
 else "wtf"
end as Status

FROM
appraisal
INNER JOIN appraisal_steps ON appraisal.`status` = appraisal_steps.step_id
WHERE
appraisal.powersale = 0
GROUP BY
DATE(appraisal.created_time),
appraisal_steps.title
ORDER BY
appraisal_steps.title DESC, status

结果对于某些状态是正确的(是复数stati?:)但是seller_answered_to_expert_question被转换为“E_Waiting”,这是不正确的。

如果我更改“When”子句的顺序,则不同的stati工作并且不起作用。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

问题是格式为CASE的{​​{1}}语句不允许通过CASE field WHEN criteria THEN ENDOR的多个条件,因此AND中的第二个条件} line没有与title字段中的值进行比较,在这种情况下,“G_Needs_Attn”,“I_Ready”或“wtf”中没有任何内容被删除。

您可以通过以下几种方式解决此问题:

将您的WHEN行分成两行:

OR

或者使用 when "expert_needs_information" then "E_Waiting" when "admin_needs_information" then "E_Waiting" 语句的格式:

CASE

此格式允许评估多个字段的条件,或同一字段的多个条件。您也可以使用 SELECT DATE(appraisal.created_time), appraisal_steps.title, Count(appraisal.appraisal_id), case when appraisal_steps.title = "archive" then "A_Archived" when appraisal_steps.title = "on_sale" then "J_Selling" when appraisal_steps.title = "under_evaluation" then "F_Evaluating" when appraisal_steps.title = "evaluated" then "H_Appraisal Complete" when appraisal_steps.title = "pending" then "B_Pending" when appraisal_steps.title = "crap" then "C_Not For Lofty" when appraisal_steps.title = "waiting_internal_expert_evaluation" then "D_Unclaimed" when appraisal_steps.title = "expert_needs_information" OR appraisal_steps.title = "admin_needs_information" then "E_Waiting" when appraisal_steps.title = "seller_answered_to_expert_question" then "G_Needs_Attn" when appraisal_steps.title = "ready_to_be_sold" then "I_Ready" else "wtf" end as Status FROM appraisal INNER JOIN appraisal_steps ON appraisal.`status` = appraisal_steps.step_id WHERE appraisal.powersale = 0 GROUP BY DATE(appraisal.created_time), appraisal_steps.title ORDER BY appraisal_steps.title DESC, status 作为该行。

以下是一个演示,展示了错误的when appraisal_steps.title IN ("expert_needs_information","admin_needs_information") then "E_Waiting"最终如何成为一个包罗万象:SQL Fiddle