简体   繁体   English

Sql 查询选择前 3 个字符

[英]Sql query for selecting the first 3 characters

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 来自 2 个表的记录,其中名为 DESC 的第一个表列(前 3 个字符)应与第二个表的项目列匹配。

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'输入:第一个表 DESC 列:值:'2AB F YY'

2nd Table Project Column: Value: '2AB'第二个表项目列:值:'2AB'

Expected Output: Return all the records of value 2AB预期 Output:返回值为 2AB 的所有记录

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

PLEASE VOID USING RESERVED KEYWORDS LIKE DESC请取消使用保留的关键字,如 DESC

SQL Fiddle SQL 小提琴

MS SQL Server 2017 Schema Setup : MS SQL 服务器 2017 架构设置

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 :查询 1

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

Results :结果

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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