2017-06-09 138 views
-1

我有代码的表像SQL JOIN表select语句

0100 ABC 
0100 ASD 
9010 ABC 
5555 ABC 

我想创建select语句,这会带给我两列像​​

calumn A (all the codes starting with 0100), column B (all the codes that after the first 4 chars, have the same ending with column A) 

例如

0100 ABC, 9010 ABC 
0100 ABC, 5555 ABC 
0100 ASD, null 

我在想像

select mtr.code, mtr1.code 
from material mtr 
where mtr.code like (%+ 

select distinct substring(mtr.code,5, len(mtr.code)) code 
from material mtr1 

) 

但它当然不起作用。有任何想法吗?

+0

是0100单个列的值,还是0100 ABC是列的值?你可以分享一下餐桌设计吗? –

+0

LIKE子查询不能返回超过1个值,看起来像它可能会返回更多,因为您正在使用DISTINCT – PawelCz

+0

表材料只有一个列字符串,所以0100 ABC和其他任何东西都是该表中的单个值 – SDAGLAS

回答

1

我认为你在寻找这样的事情:

select m1.code, m2.code 
from material m1 
left outer join material m2 
    on substring(m1.code from 5) = substring(m2.code from 5) 
    and m1.id <> m2.id 
where m1.code like '0100%' 

我们使用left outer joinmaterial得到所有行,甚至谁没有双胞胎的人。我们的连接条件是两个code值在前4个字符后必须相同。该代码还假定有一个id列;它被用来避免自己加入一行。

另一方面,如果code是您的主键,则应该使用m1.code <> m2.code来代替。

+0

工作起来就像一个魅力..谢谢 – SDAGLAS