34,872
社区成员
发帖
与我相关
我的任务
分享
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
*/
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
*/
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)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.产品数量)