Minhal
Minhal

Reputation: 85

SQL Server : select column with 3 matching characters

I am selecting the records from 2 tables in which the 1st table column named DESC (first 3 characters) should match with the project column of the 2nd table.

I want to get the last 2 characters from Table 1 column DESC to be added in my output, but the last 2 characters are not present in Table 2 column project.

select SUBSTRING(a.[DESC], 1, 3) 
from Table1 a
join Table2 b on SUBSTRING(a.[DESC], 1, 3) = b.project 

Input: 1st Table DESC Column: Value: '2AB F YY'

2nd Table Project Column: Value: '2AB'

Expected Output: Return all the records of value 2AB

Column result:

'2AB YY'

Wrong output: all the records of value starting other then 2AB

Upvotes: 0

Views: 1423

Answers (2)

George Joseph
George Joseph

Reputation: 5932

One option is as follows

with data
 as (
    select SUBSTRING(a.[DESC],1,3) as first_3_characters,
           ,REVERSE(SUBSTRING(REVERSE(a.[DESC]),1,2)) as last_2_char_tab1  
           ,REVERSE(SUBSTRING(REVERSE(b.project),1,2)) as last_2_char_tab2 characters_tab2  
      from Table1 a
      join Table2 b
        on SUBSTRING(a.[DESC],1,3) = b.project 
     )
select *,CONCAT(first_3_characters,last_2_characters)
  from data
 where last_2_char_tab1 <> last_2_char_tab2  

Upvotes: 1

LukStorms
LukStorms

Reputation: 29677

Since you don't seem to need data from Table2, an EXISTS could be used for this.

And RIGHT can be used to get the last N characters of a string.

SELECT 
 CONCAT(LEFT([DESC], 3),' ', RIGHT([DESC], 2))
FROM Table1 t1
WHERE EXISTS
(
    SELECT 1
    FROM Table2 t2
    WHERE t2.project = LEFT(t1.[DESC], 3)
)
ORDER BY 1;

Upvotes: 1

Related Questions