Sql query for selecting the first 3 characters

不打扰是莪最后的温柔 提交于 2020-01-16 09:08:09

问题


I am trying to select 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.

select SUBSTRING(a.[DESC],1,3) from Table1 a
left outer join Table2 b
on a.[DESC] = b.project
where SUBSTRING(a.[DESC],1,3) like 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


回答1:


PLEASE VOID USING RESERVED KEYWORDS LIKE DESC

SQL Fiddle

MS SQL Server 2017 Schema Setup:

CREATE TABLE Table1 ([DESC] varchar(255))
CREATE TABLE Table2 (Project varchar(255))
INSERT INTO Table1([DESC])values('2AB F YY')
INSERT INTO Table2(Project)values('2AB')

Query 1:

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

Results:

|     |
|-----|
| 2AB |



回答2:


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


来源:https://stackoverflow.com/questions/58978676/sql-query-for-selecting-the-first-3-characters

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