两个表根据条件自动匹配

wangming0605 2011-06-25 04:19:09
A表
品号,员工姓名(空)
B表
员工姓名,品号,产品数量

在A表中提取第一行数据,判断,A.品号=B.品号 AND 产品数量最大 把B.员工姓名,插入到A.员工姓名
NET第二行,同上,但是要判定每个员工姓名不能在A表中超过3次!如果超过3次,选产品数量第二大的!!
求解!!!!!!!!

...全文
108 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
叶子 2011-06-25
  • 打赏
  • 举报
回复
--SQL SERVER 2000

set nocount on

declare @A表 table (品号 int,员工姓名 varchar(10))
insert into @A表
select 1,null union all
select 2,null union all
select 3,null

declare @B表 table (员工姓名 varchar(8),品号 int,产品数量 int)
insert into @B表
select 'zhangsan',1,5 union all
select 'lisi',1,4 union all
select 'wangwu',1,6 union all
select 'zhangsan',2,2 union all
select 'lisi',2,4 union all
select 'zhangsan',3,1 union all
select 'lisi',3,4

create table #t
(id int identity,员工姓名 varchar(8),品号 int,产品数量 int)
insert into #t
select * from @B表 order by 品号,产品数量 desc

update @A表 set 员工姓名=b.员工姓名 from @A表 a
left join (select 品号,员工姓名 from
(select a.品号,a.员工姓名,rid=
(select count(*) from #t where 品号=a.品号 and id<=a.id),c.个数 from #t a
left join (select 品号,count(产品数量) as 个数 from @B表 group by 品号 )c
on a.品号=c.品号)m where (rid=1 and 个数<3) or(rid=2 and 个数>2)
)b on a.品号=b.品号

select * from @A表

drop table #t

/*
品号 员工姓名
----------- ----------
1 zhangsan
2 lisi
3 lisi
*/

叶子 2011-06-25
  • 打赏
  • 举报
回复

declare @A表 table (品号 int,员工姓名 varchar(10))
insert into @A表
select 1,null union all
select 2,null union all
select 3,null

declare @B表 table (员工姓名 varchar(8),品号 int,产品数量 int)
insert into @B表
select 'zhangsan',1,5 union all
select 'lisi',1,4 union all
select 'wangwu',1,6 union all
select 'zhangsan',2,2 union all
select 'lisi',2,4 union all
select 'zhangsan',3,1 union all
select 'lisi',3,4

;with maco as(
select row_number() over (partition by b.品号 order by 产品数量 desc) as rid,
b.品号,b.员工姓名,c.个数 from @B表 b
left join (select 品号,count(产品数量) as 个数 from @B表 group by 品号 )c
on b.品号=c.品号
)
update @A表
set 员工姓名=b.员工姓名
from @A表 a left join (
select 品号,员工姓名 from maco where (rid=1 and 个数<3) or(rid=2 and 个数>2)
)b on a.品号=b.品号

select * from @A表
/*
品号 员工姓名
----------- ----------
1 zhangsan
2 lisi
3 lisi
*/

wangming0605 2011-06-25
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 maco_wang 的回复:]
SQL SERVER 2000 还是2005+?
[/Quote]

SQL2000
cd731107 2011-06-25
  • 打赏
  • 举报
回复

insert a(员工姓名,品号)
select b.员工姓名,b.品号
from b,a
where a.品号=b.品号
and not exists
(select 1 from b as tb where tb.品号=b.品号 and tb.产品数量>b.产品数量)
and b.员工姓名 not in (select 员工姓名 from a group by 员工姓名 having count(*)>3)
cd731107 2011-06-25
  • 打赏
  • 举报
回复
insert a(员工姓名,品号) 
select b.员工姓名,b.品号
from b,a
where a.品号=b.品号
and not exists
(select 1 from b as tb where tb.品号=b.品号 and tb.产品数量>b.产品数量)
叶子 2011-06-25
  • 打赏
  • 举报
回复
SQL SERVER 2000 还是2005+?

34,872

社区成员

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

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