如下的SQL需求,请大家帮忙写一下:
A表有a,b,c两列,B表有c,d两列
A表
a        b
a01      10
a02      8
a03      7
B表
a        c        d
a01      b01      1
a01      b02      2
a01      b03      5
a02      b04      1
a02      b05      4
a03      b06      1
a03      b07      3
其中A表中的b列时不断更新的。我的需求是,当A表的b列能被B表的d列中最大的一个值整除时,取b表中相应的记录,即得到以下结果:
a        b        c        d
a01      10       b03      5
a02      8        b05      4
a03      7        b06      1

解决方案 »

  1.   

    select * from A表 a left join B表 b on a.a=b.a
     where a.b%b.d=0
      

  2.   

    --A表有a,b,c两列,B表有c,d两列
    create table A(a varchar(10),b int)
    insert a
    select 'a01', 10 union all
    select 'a02', 8 union all
    select 'a03', 7
    --B表
    create table B(a varchar(10),c varchar(10),d int)
    insert B
    select 'a01', 'b01', 1  union all
    select 'a01', 'b02', 2 union all
    select 'a01', 'b03', 5 union all
    select 'a02', 'b04', 1 union all
    select 'a02', 'b05', 4 union all
    select 'a03', 'b06 ',1 union all
    select 'a03', 'b07', 3
    select a.*,(select top 1 d from b  where a.a=b.a and a.b%b.d=0 order by d desc)    from a 
      

  3.   


    declare @A表 table (a varchar(3),b int)
    insert into @A表
    select 'a01',10 union all
    select 'a02',8 union all
    select 'a03',7declare @B表 table (a varchar(3),c varchar(3),d int)
    insert into @B表
    select 'a01','b01',1 union all
    select 'a01','b02',2 union all
    select 'a01','b03',5 union all
    select 'a02','b04',1 union all
    select 'a02','b05',4 union all
    select 'a03','b06',1 union all
    select 'a03','b07',3select a.*,b.c,b.d from @A表 a
    left join (select * from @B表 t
    where d=(select max(d) from @B表 where a=t.a))
    b on a.a=b.a
    /*
    a    b           c    d
    ---- ----------- ---- -----------
    a01  10          b03  5
    a02  8           b05  4
    a03  7           b07  3
    */
      

  4.   

    借用楼上数据;with test as(
    select a.a,a.b,b.c,b.d from A inner join B on A.a=B.a where a.b%b.d=0)
    select * from test t where d=(select max(d) from test where a=t.a)
    order by aa          b           c          d
    ---------- ----------- ---------- -----------
    a01        10          b03        5
    a02        8           b05        4
    a03        7           b06        1