SQL语句中的case语句和OR

时间:2017-03-07 16:22:37

标签: sql tsql

有人可以在下面提出建议吗?我有许多我想使用的字段,并将它们组合在一起以获取数据。我正在使用以下案例陈述但未得到我期望的结果。

CASE
WHEN m.u_hearing = 1 THEN 'Hearing'
WHEN m.u_learning_reading_diff = 1 THEN 'Learning or reading Difficulty'
WHEN m.u_long_term_ill = 1 THEN 'Long Term Illness'
WHEN m.u_mental_illness = 1 THEN 'Mental Illness'
WHEN m.u_mobility = 1 THEN 'Mobility'
WHEN m.u_physical_coordination = 1 THEN 'Physical Co-ordination'
WHEN m.u_physical_dis = 1 THEN 'Physical Disability'
WHEN m.u_red_physical_cap = 1 THEN 'Reduced_physical_capacity'
WHEN m.u_speech = 1 THEN 'Speech'
WHEN m.u_vision = 1 THEN 'Vision'
WHEN m.u_other_dis = 1 THEN 'Other_Disability'
WHEN (m.u_hearing = 1 AND (m.u_learning_reading_diff = 1 OR (m.u_speech = 1))) THEN 'Multiple'

这是最后一个没有给出我想要的结果的语句,好像有多个字段是,然后我想要多个返回,但它似乎是在挑选第一个案例。

3 个答案:

答案 0 :(得分:1)

将“最难”的条件放在第一位

case WHEN m.u_hearing = 1 AND (m.u_learning_reading_diff = 1 OR m.u_speech = 1) THEN 'Multiple' 
     WHEN m.u_hearing = 1 THEN 'Hearing' ...

因为casetrue

的第一个条件停止

答案 1 :(得分:0)

使用CASE语句时,它们将按照您指定的顺序运行。

因此,如果m.u_Hearing = 1,它将停在第一行,而不是到达底部。

这将适合您的需要,但请按您喜欢的顺序列出。

CASE
WHEN (m.u_hearing = 1 AND (m.u_learning_reading_diff = 1 OR (m.u_speech = 1))) THEN 'Multiple'
WHEN m.u_hearing = 1 THEN 'Hearing'
WHEN m.u_learning_reading_diff = 1 THEN 'Learning or reading Difficulty'
WHEN m.u_long_term_ill = 1 THEN 'Long Term Illness'
WHEN m.u_mental_illness = 1 THEN 'Mental Illness'
WHEN m.u_mobility = 1 THEN 'Mobility'
WHEN m.u_physical_coordination = 1 THEN 'Physical Co-ordination'
WHEN m.u_physical_dis = 1 THEN 'Physical Disability'
WHEN m.u_red_physical_cap = 1 THEN 'Reduced_physical_capacity'
WHEN m.u_speech = 1 THEN 'Speech'
WHEN m.u_vision = 1 THEN 'Vision'
WHEN m.u_other_dis = 1 THEN 'Other_Disability'

答案 2 :(得分:0)

据我所知,你不能在另一个“何时”再次使用你的第一个陈述

WHEN m.u_hearing = 1 THEN 'Hearing'

以上条件尝试使用else,如果它最终可行并且可行。

Else 'Multiple'