现有两表如下: 
create table tt(a nvarchar(20),b nvarchar(20)) 
insert into tt values('E10','出厂') 
insert into tt values('E20','出厂排产') 
insert into tt values('E30','安装完工') create table dd(c nvarchar(40)) 
insert into dd values('出厂排产完工日7天后')
insert into dd values('出厂完工日7天后')
insert into dd values('安装完工7天后')
我想得到结果: 
     c                b
出厂排产完工日7天后  E20  
出厂完工日7天后      E10  
安装完工10天后       E30  应该怎么写

解决方案 »

  1.   

    类似的问题
    declare  @tt table(a varchar(20),b varchar(20)) 
    insert into @tt values('E10','a') 
    insert into @tt values('E20','ab') declare  @dd table(c varchar(40)) 
    insert into @dd values('ab123')  select  a.a,b.c from @tt a,@dd b 
    where a.b=left(b.c,patindex('%[0-9]%',b.c)-1)
    /*
    a                    c                                        
    E20                  ab123
      

  2.   

    create table tt1(a nvarchar(20),b nvarchar(20)) 
    insert into tt1 values('E10','出厂') 
    insert into tt1 values('E20','出厂排产') 
    insert into tt1 values('E30','安装完工') create table dd1(c nvarchar(40)) 
    insert into dd1 values('出厂排产完工日7天后') 
    insert into dd1 values('出厂完工日7天后') 
    insert into dd1 values('安装完工7天后') select A,c
    from tt1 k ,dd1 t
    where CHARINDEX(b,c)>0 and not exists(select * from tt1 where  CHARINDEX(b,t.c)>0 and b<>k.b)
    union all
    select A,c
    from tt1 k ,dd1 t
    where CHARINDEX(b,c)>0 and A not IN (
    select A
    from tt1 k ,dd1 t
    where CHARINDEX(b,c)>0 and not exists(select * from tt1 where  CHARINDEX(b,t.c)>0 and b<>k.b))
    /*
    A                    c
    -------------------- ----------------------------------------
    E10                  出厂完工日7天后
    E30                  安装完工7天后
    E20                  出厂排产完工日7天后(3 行受影响)
    */
      

  3.   

    呵呵,都是我问的如果dd表只有一条的话可以这样
    SQL code
    select top 1 tt.a,dd.c from tt left join dd on charindex(tt.b,dd.c)>0 order by len(b) desc如果像我现在问的这样,有多条怎么办呀
     
     
      

  4.   

    加上条件,去除重复值
    select *
    from aa as a
    where not exists(select 1 from aa where ms = a.ms and sname < a.sname)