简体   繁体   中英

SQL Server 2008 R2: Pattern matching string vice versa

I have the following table:

Table:

CREATE TABLE str_matching
(
    colstr varchar(200)
);

Insert data:

INSERT INTO str_matching VALUES('5sXYZA1010B')
INSERT INTO str_matching VALUES('A1010B')
INSERT INTO str_matching VALUES('AMZ103B15K')
INSERT INTO str_matching VALUES('B15K')
INSERT INTO str_matching VALUES('XC101')
INSERT INTO str_matching VALUES('C101')
INSERT INTO str_matching VALUES('502KMD1FZ10009L')
INSERT INTO str_matching VALUES('FZ10009L')
INSERT INTO str_matching VALUES('A9L')
INSERT INTO str_matching VALUES('XZ049L')
INSERT INTO str_matching VALUES('LM101')
INSERT INTO str_matching VALUES('9001')
INSERT INTO str_matching VALUES('9001A')

Expected Output: I want to display only those records that has duplicate entries, if one string match last part of any string then I am considering as duplicate.

Scenario : 1

For example: I have two strings

  1. 5sXYZA1010B
  2. A1010B

2nd string which is matching at end of 1st string, so want to display such records.

Scenario : 2

For example: I have two strings

  1. 9001
  2. 9001A

1st string which is matching at first of 2nd string, so want to display such records.

Note : Length of string's are not fixed, it can be match at any point.

Expected Result:

colstr              
--------------------
5sXYZA1010B         
A1010B              
AMZ103B15K          
B15K                
XC101               
C101                
502KMD1FZ10009L     
FZ10009L    
9001
9001A   

Note: Need to check the vice versa pattern matching.

As per Martin Smith code, I have modified to:

SELECT DISTINCT CA.colstr
FROM   str_matching s1
       JOIN str_matching s2
         ON s1.colstr <> s2.colstr
            AND s2.colstr LIKE '%' + s1.colstr 
            OR s1.colstr LIKE '%' + s2.colstr
       CROSS APPLY (VALUES(s1.colstr),
                          (s2.colstr)) CA(colstr) 

But unable to get the given set of strings.

You just need to fix your logic:

SELECT DISTINCT CA.colstr
FROM str_matching s1 JOIN
     str_matching s2
     ON s1.colstr <> s2.colstr AND
        (s2.colstr LIKE s1.colstr + '%' OR
         s1.colstr LIKE s2.colstr + '%'
        ) CROSS APPLY
     (VALUES(s1.colstr), (s2.colstr)) as CA(colstr) ;

You had the LIKE patterns backwards and needed parens around the join conditions.

This works for me:

SELECT DISTINCT CA.colstr
FROM str_matching s1 JOIN
 str_matching s2
 ON s1.colstr <> s2.colstr AND
    (s1.colstr LIKE s2.colstr + '%' OR
     s2.colstr LIKE '%'+ s1.colstr 
    ) CROSS APPLY
 (VALUES(s1.colstr), (s2.colstr)) as CA(colstr) ;

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