简体   繁体   中英

Using regular expression in SQL to read the values for an attribute

I am working on Snowflake to look for values for a string in a particular field. For example, I have a column called col1 with two values as follows

1. |LFD: |**Wed 07 Jul 2021**|
2. LFD & additional info

Here in the first record we have value for string LFD , given as July 7,2021. But in second row we don't have value for LFD.

I tried to create a boolean flag as follows;

case when col1 ilike '%LFD%' then 0 else 1 end as LFD_missing_flag

Interestingly it is giving 0 for both rows, but it shd be giving 1 for second row and 0 for first row. Expected Output

    col1                              LFD_missing_flag
  |LFD: |**Wed 07 Jul 2021**|   |      0
             
   LFD & additional info.       |      1

Since in second row we don't have value for LFD, it shd be 1, otherwise 0, as seen for first record.

Modifications Along the same lines I have following piece of text;

|FIRMS Code: |**Unknown**|
|FIRMS Code: |**WAM7**|
|FIRMS Code: |WAM7|

For this case the output shd be;

col1                           FIRMS_flag
|FIRMS Code: |**Unknown**|        1
|FIRMS Code: |**WAM7**|.          0
|FIRMS Code: |WAM7|.              0

Can I get help to modify my logic so that I can get the correct output? thanks

So given both input strings appear to have the sub-string LFD in them search for just that is not enough, the row to want result does have a : also so we can add that:

SELECT 
    column1
    ,column1 ilike '%lfd%' as _like
    ,column1 ilike '%lfd:%' as not_like
    ,(column1 not ilike '%lfd:%')::int as results_a
    ,iff(column1 ilike '%lfd:%', 0, 1) as results_b
    ,case when column1 ilike '%LFD:%' then 0 else 1 end as results_c
FROM VALUES
    ('|LFD: |**Wed 07 Jul 2021**|'),
    ('LFD & additional info')

which gives:

COLUMN1 _LIKE NOT_LIKE RESULTS_A RESULTS_B RESULTS_C
|LFD: |**Wed 07 Jul 2021**| TRUE TRUE 0 0 0
LFD & additional info TRUE FALSE 1 1 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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