现在有3个仓库,存放两种不同的货物,我现在有一批货物将要入库,由于每个仓库一次只能处理一个货物的入库操作,那么多个货物入库,需要多次操作来完成。 表1 
仓库Id   货物类型 
1         a 
2         b 
3         b 表2 
货物id    货物类型 
1         a 
2         a 
3         b 
4         a 
5         b 
希望通过SQL 对两张表 联合查询,得到如下表格,以实现入库操作 
库位id      货物id 
1            1 
2            3 
3            5
请教一下,这个SQL语句该怎么书写呀?

解决方案 »

  1.   

    if object_id('tb1') is not null drop table tb1 
     go 
    create table tb1([仓库Id] int,[货物类型] varchar(10))
    insert tb1 select 1,'a'
    union all select 2,'b'
    union all select 3,'b'
    go
    if object_id('tb2') is not null drop table tb2 
     go 
    create table tb2([货物id] int,[货物类型] varchar(10))
    insert tb2 select 1,'a'
    union all select 2,'a'
    union all select 3,'b'
    union all select 4,'a'
    union all select 5,'b'
    go
    select 
        a.[仓库Id],
        b.[货物id]
    from 
    (
      select px=(select count(1) from tb1 where [货物类型]=t.[货物类型] and [仓库Id]<=t.[仓库Id]),* from tb1 t
    ) a
    join
    (
      select px=(select count(1) from tb2 where [货物类型]=t.[货物类型] and [货物id]<=t.[货物id]),* from tb2 t
    ) b 
      on a.px=b.px and a.[货物类型]=b.[货物类型]
    /*
    仓库Id        货物id
    ----------- -----------
    1           1
    2           3
    3           5(3 行受影响)
    */