表A :ID 流水号 单位名称
     1   10001  单位A
     2   10001  单位B
     3   10002  单位C
    表B: 流水号 项目名
      10001 项目A
      10002 项目B
想得到这样的数据: 
流水号 项目名 单位名
10001   项目A  单位A
10002   项目B  单位C每个流水号只在表A里取第1条满足条件的数据。

解决方案 »

  1.   

      select A.*,B.*
      from A
      cross apply(select top 1 from b where .a流水号=b.流水号) B
      

  2.   

    select m.* , n.单位名称 单位名
    from b m, a n
    where m.流水号 = n.流水号 and n.ID = (select min(id) from a where a.流水号 = n.流水号)select m.* , n.单位名称 单位名
    from b m, a n
    where m.流水号 = n.流水号 and not exists (select 1 from a where a.流水号 = n.流水号 and a.id < n.id) 
      

  3.   

    create table #A
    (
       id int,
       idno int,
       name varchar(10)
    )
    insert into #A
    select 1,10001,'A' union all
    select 2,10001,'B' union all
    select 3,10002,'C' create table #B
    (
       idno int,
       value varchar(10)
    )
    insert into #B
    select 10001,'Aa' union all
    select 10002,'BB'select a.idno,a.name,b.value from (select idno,max(name) name from #A group by idno) a
    right join #B b on a.idno=b.idno
      

  4.   

    create table A(ID int,流水号 varchar(10),单位名称 varchar(10))
    insert into a values(1 ,'10001', '单位A')
    insert into a values(2 ,'10001', '单位B')
    insert into a values(3 ,'10002', '单位C')
    create table B(流水号  varchar(10),项目名 varchar(10))
    insert into b values('10001', '项目A')
    insert into b values('10002', '项目B')
    goselect m.* , n.单位名称 单位名
    from b m, a n
    where m.流水号 = n.流水号 and n.ID = (select min(id) from a where a.流水号 = n.流水号)
    /*
    流水号        项目名        单位名        
    ---------- ---------- ---------- 
    10001      项目A        单位A
    10002      项目B        单位C(所影响的行数为 2 行)
    */select m.* , n.单位名称 单位名
    from b m, a n
    where m.流水号 = n.流水号 and not exists (select 1 from a where a.流水号 = n.流水号 and a.id < n.id) 
    /*
    流水号        项目名        单位名        
    ---------- ---------- ---------- 
    10001      项目A        单位A
    10002      项目B        单位C(所影响的行数为 2 行)
    */drop table a , b