简体   繁体   English

SQL喜欢多条语句

[英]SQL Like with multiple statements

So I have the following query which does not give back the right results and I do not know why: 因此,我有以下查询无法返回正确的结果,而且我也不知道为什么:

Sample data: 样本数据:

LIST1 | LIST2
APRIL | NOLA
NOLA  | BEBB
NOLA  | APROLS
APRA  | BLIN

The query: 查询:

SELECT LIST1, 
       LIST2, 
       CASE WHEN (([LIST1] LIKE '%APR%' 
                   OR [LIST1] LIKE '%NOLA%') 
             AND ([LIST2] NOT LIKE '%APR%' 
                   AND [LIST2] NOT LIKE '%NOLA%')) 
            THEN 1 
            ELSE 0 
       END AS RESULTS

It gives back 1 for both rows. 两行都返回1。 It should give back 0 for the first row. 它应该为第一行返回0。 So I would expect the following output 所以我期望以下输出

LIST1 | LIST2 | RESULTS
APRIL | NOLA  | 0
NOLA  | BEBB  | 1
NOLA  | APROLS| 0
APRA  | BLIN  | 1

What is my mistake here? 我这是什么错 The output should be 0 for those two cases as I have clearly put in an 'AND' statement. 正如我在“ AND”语句中明确指出的那样,对于这两种情况,输出应该为0。

SELECT LIST1, 
       LIST2, 
       CASE 
          WHEN (([LIST1] LIKE '%APR%' 
                 OR [LIST1] LIKE '%NOLA%') 
           OR ([LIST2] NOT LIKE '%APR%' 
                AND [LIST2] NOT LIKE '%NOLA%')) 
          THEN 1 
          ELSE 0 
       END AS RESULTS

LIST1   LIST2   RESULTS
APRIL   NOLA    1
NOLA    BEBB    1
NOLA    APROLS  1
APRA    BLIN    1

it gives you for both case 1 because [LIST1] LIKE '%APR%' OR [LIST1] LIKE '%NOLA%' this line is true for 'APRIL' of 1st row value of list1 and again it is true for 'NOLA' for 2nd row and when any portion of will true of or condition then full condition will be true. 它为您提供两种情况1,因为[LIST1] LIKE '%APR%' OR [LIST1] LIKE '%NOLA%'这条线对于list1的第一行值的'APRIL'是正确的,对于'NOLA'也是这样对于第二行,当will的任何一部分为true或条件时,则完全条件为true。 As a result you got both case 1 结果,您遇到了两种情况1

but if you put and condition then result will be as your expectation 但是如果您放置and调整条件,结果将如您所愿

SELECT LIST1, 
       LIST2, 
       CASE WHEN (
         (
           [LIST1] LIKE '%APR%' 
                   OR [LIST1] LIKE '%NOLA%') 
             AND 
         (
                  [LIST2] NOT LIKE '%APR%' 
                   AND [LIST2] NOT LIKE '%NOLA%')

          ) 
            THEN 1 
            ELSE 0 
       END AS RESULTS from t

http://sqlfiddle.com/#!18/9f8c5/1 http://sqlfiddle.com/#!18/9f8c5/1

LIST1   LIST2   RESULTS
APRIL   NOLA    0
NOLA    BEBB    1
NOLA    APROLS  0
APRA    BLIN    1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM