SQL Server : select column with 3 matching characters

徘徊边缘 提交于 2020-01-16 09:09:29

问题


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


回答1:


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  



回答2:


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;


来源:https://stackoverflow.com/questions/58980575/sql-server-select-column-with-3-matching-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!