0

我正在尝试重命名我具有只读访问权限的数据库的一列的值。我还想将其中两个值合二为一。我正在使用 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

某些状态的结果是正确的(是复数状态吗?:),但卖主回答到专家问题被转换为“E_Waiting”,这是不正确的。

如果我更改“When”子句的顺序,则不同的 stati 有效且无效。

我究竟做错了什么?

4

1 回答 1

2

问题是,CASE格式为 like 的语句CASE field WHEN criteria THEN END不允许通过多个标准,OR因此ANDWHEN行中的第二个标准没有与您的标题字段中的值进行比较,“G_Needs_Attn”,“I_Ready”中没有任何内容,或在这种情况下为“wtf”。

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

将您的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"用于该行。

这是一个演示,展示了错误OR最终如何成为一个包罗万象的:SQL Fiddle

于 2013-07-09T04:13:09.400 回答