请教一SQL语句

ruanuxan 2011-03-23 11:11:40
现在有两个表
表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表中的编号可能属于不同的部门,但是在组合查询结果中只随机取一个部门名称就可以了,请教各位大侠语句如何实现?


...全文
82 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
快溜 2011-03-23
  • 打赏
  • 举报
回复
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 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
天-笑 2011-03-23
  • 打赏
  • 举报
回复


declare @a table (BH INT ,SL FLOAT)
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

--小F-- 2011-03-23
  • 打赏
  • 举报
回复
select
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)
快溜 2011-03-23
  • 打赏
  • 举报
回复
select BH,BM=(select top 1 BM from tb2 where BH=a.BH),SL 
from tb1 a
ruanuxan 2011-03-23
  • 打赏
  • 举报
回复
谢谢各位!!

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧