现在有两个表
表A
BH SL
1001 200
1002 300
1003 400
。。
表B
BH BM
1001 仓库1
1002 仓库2
1001 仓库2
1003 仓库3
。
现在想连接两表查询得如下结果
BH BM SL
1001 仓库1 200
1002 仓库2 300
1003 仓库3 400
。。意思就是B表中的编号可能属于不同的部门,但是在组合查询结果中只随机取一个部门名称就可以了,请教各位大侠语句如何实现?
表A
BH SL
1001 200
1002 300
1003 400
。。
表B
BH BM
1001 仓库1
1002 仓库2
1001 仓库2
1003 仓库3
。
现在想连接两表查询得如下结果
BH BM SL
1001 仓库1 200
1002 仓库2 300
1003 仓库3 400
。。意思就是B表中的编号可能属于不同的部门,但是在组合查询结果中只随机取一个部门名称就可以了,请教各位大侠语句如何实现?
from tb1 a
b.*,a.sl
from
a join b t
on
a.bu=b.bu
and
t.bh=(select max(bh) from tb where bm=t.bm)
insert into @A
select 1001,200 union all
select 1002,300 union all
select 1003,400
declare @B table (BH INT ,BM VARCHAR(8))
insert into @B
select 1001,'仓库1' union all
select 1002,'仓库2' union all
select 1001,'仓库2' union all
select 1003,'仓库3'
SELECT * FROM @a A LEFT JOIN
( SELECT BH,MIN(BM) AS bm FROM @B GROUP BY BH
)
B ON A.BH = B.BH-----------------------
1001 200 1001 仓库1
1002 300 1002 仓库2
1003 400 1003 仓库3
insert into @B
select 1001,'仓库1' union all
select 1002,'仓库2' union all
select 1001,'仓库2' union all
select 1003,'仓库3'select BH,BM=(select top 1 BM from @B where BH=a.BH),SL
from @a a/*
BH BM SL
----------- -------- -----
1001 仓库1 200
1002 仓库2 300
1003 仓库3 400