alter table 表a add 代码 varchar(8)
update a set a.代码=b.代码 from 表a a,表b b where a.单位=b.单位 and a.地址=b.地址
select * from 表a不知道楼主是不是这样的意思?我是在表A中加的 代码可以是c1-1或c1-2,但不能是c1-1或c2-1其它的代码?这句话不是很明白
update a set a.代码=b.代码 from 表a a,表b b where a.单位=b.单位 and a.地址=b.地址
select * from 表a不知道楼主是不是这样的意思?我是在表A中加的 代码可以是c1-1或c1-2,但不能是c1-1或c2-1其它的代码?这句话不是很明白
单位 地址 代码 数量
a1 b1-1 c1-1 20
a1 b1-1 c1-2 21
a1 b1-1 c1-1 22
a1 b1-2 c1-3 20
也就是说:
单位a1,地址b1-1有两类代码c1-1,c1-2,可选其中一个,但不能选
单位a1,地址b1-2的代码c1-3
declare @tb1 table(单位 char(2),地址 char(10),总量 int)
insert into @tb1
select 'a1','b1-1',500 union all
select 'a1','b1-2',500 union all
select 'a2','b2-1',500 union all
select 'a2','b2-2',500 union all
select 'a3','b3-1',500 union all
select 'a4','b3-1',500 union all
select 'a4','b3-2',500declare @tb2 table(单位 char(2),地址 char(10),代码 char(10),数量 int)
insert into @tb2
select 'a1','b1-1','c1-1',20 union all
select 'a1','b1-1','c1-2',21 union all
select 'a1','b1-1','c1-1',22 union all
select 'a1','b1-2','c1-3',20 union all
select 'a1','b1-1','c1-1',21 union all
select 'a1','b1-1','c1-1',22 union all
select 'a2','b2-1','c2-2',20 union all
select 'a2','b2-1','c2-1',21 union all
select 'a2','b2-1','c2-1',22 union all
select 'a2','b2-2','c2-3',20 union all
select 'a2','b2-1','c2-1',21 union all
select 'a2','b2-1','c2-1',22 union all
select 'a3','b3-1','c3-1',23 union all
select 'a3','b3-1','c3-1',22 union all
select 'a3','b3-1','c3-1',23 union all
select 'a4','b3-1','c4-1',23 union all
select 'a4','b3-1','c4-1',22 union all
select 'a4','b3-1','c4-1',23 union all
select 'a4','b3-2','c4-1',23 union all
select 'a4','b3-2','c4-1',23
select a.单位,a.地址,b.代码,a.总量 from @tb1 a left join (select 单位,地址,代码=max(代码) from @tb2 group by 单位,地址)b on a.单位=b.单位 and a.地址=b.地址
/*
单位 地址 代码 总量
---- ---------- ---------- -----------
a1 b1-1 c1-2 500
a1 b1-2 c1-3 500
a2 b2-1 c2-2 500
a2 b2-2 c2-3 500
a3 b3-1 c3-1 500
a4 b3-1 c4-1 500
a4 b3-2 c4-1 500(所影响的行数为 7 行)
*/