编号从另两表获得。
表1
产品类别 类别编号
主机 A
主板 B
内存 C
表2
编号 名称 产品类别
A001 DELL 主机
B001 技嘉 主板
A002 惠普 主机
表3
编号 名称 产品类别
NULL 联想 主机
NULL 金士顿 内存
NULL 日立 主机
现想从表1取编号+表2最大编号 得到表3的编号,即:
表3
编号 名称 产品类别
A003 联想 主机
C001 金士顿 内存
A004 日立 主机
请教这SQL语法。
[解决办法]
select 表1.类别编号 + max(表2.编号) as '编号' ,表2.名称 ,表2.产品类别 from 表1 left join 表2
on 表1.产品类别 =表2.产品类别
[解决办法]
- SQL code
--> 测试数据:[表1]if object_id('[表1]') is not null drop table [表1]create table [表1]([产品类别] varchar(4),[类别编号] varchar(1))insert [表1]select '主机','A' union allselect '主板','B' union allselect '内存','C'--> 测试数据:[表2]if object_id('[表2]') is not null drop table [表2]create table [表2]([编号] varchar(4),[名称] varchar(4),[产品类别] varchar(4))insert [表2]select 'A001','DELL','主机' union allselect 'B001','技嘉','主板' union allselect 'A002','惠普','主机'--> 测试数据:[表3]if object_id('[表3]') is not null drop table [表3]create table [表3]([编号] varchar(4),[名称] varchar(6),[产品类别] varchar(4))insert [表3]select null,'联想','主机' union allselect null,'金士顿','内存' union allselect null,'日立','主机'withm as(select px=ROW_NUMBER()over(partition by [产品类别] order by [编号] DESC,(select 1)),* from(select * from [表2]union allselect * from [表3])t),n as(select a.类别编号+right('000'+LTRIM(px),3) as 类别编号,[名称],m.[产品类别]from [表1] aleft join mon a.产品类别=m.产品类别where m.编号 is null)update [表3]set [编号]=n.类别编号 from n where [表3].产品类别=n.产品类别 and [表3].名称=n.名称select * from [表3]/*编号 名称 产品类别--------------------------------A003 联想 主机C001 金士顿 内存A004 日立 主机*/
[解决办法]
- SQL code
if object_id('[t1]') is not null drop table [t1]gocreate table [t1]([产品类别] varchar(4),[类别编号] varchar(1))insert [t1]select '主机','A' union allselect '主板','B' union allselect '内存','C'goif object_id('[t2]') is not null drop table [t2]gocreate table [t2]([编号] varchar(4),[名称] varchar(4),[产品类别] varchar(4))insert [t2]select 'A001','DELL','主机' union allselect 'B001','技嘉','主板' union allselect 'A002','惠普','主机'goif object_id('[t3]') is not null drop table [t3]gocreate table [t3]([编号] varchar(4),[名称] varchar(6),[产品类别] varchar(4))insert [t3]select null,'联想','主机' union allselect null,'金士顿','内存' union allselect null,'日立','主机'goalter table t3 add tid int identity(1,1);goupdate a set 编号=t1.类别编号+right('000'+ltrim(b.编号+(select count(1) from t3 where 产品类别=a.产品类别 and tid<=a.tid)),3)from t3 ajoin(select t1.产品类别,t1.类别编号,isnull(replace(max(t2.编号),t1.类别编号,''),'0') as 编号from t1 left join t2 on t1.产品类别=t2.产品类别group by t1.产品类别,t1.类别编号) bon a.产品类别=b.产品类别join t1 on a.产品类别=t1.产品类别goalter table t3 drop column tid;goselect * from t3/**编号 名称 产品类别---- ------ ----A003 联想 主机C001 金士顿 内存A004 日立 主机(3 行受影响)**/