T1
编号      名称      条码
1001      水       111
1001     开水      111
1002     茶        222
1002     绿茶      222
1003     烟        333
1004     酒        333T2
编号     名称    
1001     水
1002     茶
1003     烟
1004     酒
........结果
T2
编号     名称     条码
1001     水1      111
1002     茶2     222
1003     烟3      333
1004     酒4      444
我用join t2 on t1.编号=t2.编号这个语句的时候,如果T1表中相同的编号有多条,那显示出来的结果也会是多条,应该如何判断?

解决方案 »

  1.   

    select b.*
    from T2 a join T1 b
    on a.编号=b.编号 and b.名称=(select top 1 名称 from T1 where 编号=b.编号 order by 名称)
      

  2.   

    好像这样更简单select b.*
    from T2 a join T1 b
    on a.编号=b.编号 and b.名称=a.名称
      

  3.   

    if object_id('[t1]') is not null drop table [t1]
    go
    create table [t1]([编号] int,[名称] varchar(4),[条码] int)
    insert [t1]
    select 1001,'水',111 union all
    select 1001,'开水',111 union all
    select 1002,'茶',222 union all
    select 1002,'绿茶',222 union all
    select 1003,'烟',333 union all
    select 1004,'酒',333
    if object_id('[t2]') is not null drop table [t2]
    go
    create table [t2]([编号] int,[名称] varchar(2))
    insert [t2]
    select 1001,'水' union all
    select 1002,'茶' union all
    select 1003,'烟' union all
    select 1004,'酒'select * from [t1]
    select * from [t2]select t2.[编号],t2.[名称]+right(t2.[编号],1),a.[条码]
    from (select distinct [编号],[条码] from T1) a
    join T2
    on a.[编号]=T2.[编号]
    --测试结果:
    /*
    编号               条码
    ----------- ---- -----------
    1001        水1   111
    1002        茶2   222
    1003        烟3   333
    1004        酒4   333(4 行受影响)*/