SQL - CASE WHEN麻烦

时间:2015-02-24 18:29:40

标签: sql case-when

使用CASE WHEN语句遇到问题。下面的示例脚本:

SELECT
    CASE WHEN Column1 = "Example 1" THEN "Name 1"
         WHEN Column1 = "Example 2" THEN "Name 2"
         WHEN Column1 = "Example 3" THEN "Name 3"
         WHEN Column1 = "Example 3" AND Column2 IN ("Sample1", "Sample2") THEN "Name4"
         WHEN Column1 = "Example 3" AND Column2 IN ("Sample3", "Sample4") THEN "Name5"
         ELSE "-" END AS Name,

    [aggregation language that doesn't affect the script]

FROM Table1
GROUP BY Name
HAVING Name IN ("Name1", "Name2", "Name3", "Name4", "Name5"
ORDER BY Name ASC

我遇到的问题是,在执行脚本" Name1"," Name2"和" Name3"所有拉(并准确拉),但" Name4"和" Name5"根本没有拉动,大概是因为他们与" Name3" (Column1 =" Example3")。

基本上,我试图同时提取" Name3"它的组成部分是" Name4"和" Name5"。

考虑它的一种方法是" Name3"是NFL和" Name4"和" Name5"分别是AFC和NFC。因为我在条件{Column1 =" Example3"}中拉入NFL,它不会拉入AFC和NFC,尽管需要第二个" AND&# 34;条件。

如果有人能在这里提供帮助,那就太爱了。我尝试过使用括号,改变WHEN的顺序......没有运气。

提前致谢!

3 个答案:

答案 0 :(得分:4)

我的建议是改变案件的顺序:

SELECT
    CASE WHEN Column1 = "Example 1" THEN "Name 1"
         WHEN Column1 = "Example 2" THEN "Name 2"
         WHEN Column1 = "Example 3" AND Column2 IN ("Sample1", "Sample2") THEN "Name4"
         WHEN Column1 = "Example 3" AND Column2 IN ("Sample3", "Sample4") THEN "Name5"
         WHEN Column1 = "Example 3" THEN "Name 3" 
         ELSE "-" END AS Name,

    [aggregation language that doesn't affect the script]

FROM Table1
GROUP BY Name
HAVING Name IN ("Name1", "Name2", "Name3", "Name4", "Name5"
ORDER BY Name ASC

根据您当前的订购,如果“Name4”或“Name5”为真,“名称3”将始终为真,因此将首先执行。使用修改后的顺序,只有当“Name4”和“Name5”出现错误时,“Name 3”才会成立。有意义吗?

答案 1 :(得分:1)

  

如果有人能在这里提供帮助,那就太爱了。我尝试过使用括号,改变WHEN的顺序......没有运气。

你不是完全诚实的,是吗?

http://sqlfiddle.com/#!6/11381/3/0 - WHEN条件的简单切换可以解决您的小问题。这里的教训是,测试在第一个条件下停止,这是真的。

答案 2 :(得分:0)

对于“姓名3”,您需要排除“姓名4”和“姓名5”的条件:

CASE WHEN Column1 = "Example 1" THEN "Name 1"
     WHEN Column1 = "Example 2" THEN "Name 2"
     WHEN Column1 = "Example 3"
       AND Column2 NOT IN ("Sample1", "Sample2", "Sample3", "Sample4") THEN "Name 3"
     WHEN Column1 = "Example 3" AND Column2 IN ("Sample1", "Sample2") THEN "Name4"
     WHEN Column1 = "Example 3" AND Column2 IN ("Sample3", "Sample4") THEN "Name5"
     ELSE "-" END AS Name,

case when从第一个匹配条件返回,然后忽略其余条件,因此您需要使较早的条件变窄。或者,您可以将Name4 / 5条件放在Name 3条件之前。