SQL怎样给查询出来的数据自动编号[分不多了>..<,望包含~~]
如题:
我有一个序号表A
A01[序号]
---------
M001
M002
表B查询出来的内容是:
其中B01的内容全部是相同的,现在想结合表A接着M002编号。
原始表B的内容是:
B01[编号] B02[内容]
-------------------
11 xx
11 yy
编号号想得到如下结果:
B01[编号] B02[内容]
-------------------
M003 xx
M004 yy
即B01的编号接着表A的A01的最后的编号编.
------解决方案--------------------declare @max int
set @max=2 --a表的最大序号
select 'M'+RIGHT('000'+cast(ROW_NUMBER() over(ORDER by getdate()) as varchar(10)),3) as B01,B02
from B
------解决方案--------------------create table ta(a01 varchar(10))
create table tb(b01 int,b02 varchar(10))
insert into ta select 'M001' union all select 'M002'
insert into tb select 11,'xx' union all select 11,'yy'
go
;with c1 as(
select ROW_NUMBER()Over(order by b02)rn,b02 from tb
),c2 as(
select top 1 convert(int,right(a01,2))id from ta a where not exists(select 1 from ta where a01>a.a01)
)select 'M'+right('00'+ltrim(a.rn+b.id),2)as b01,a.b02 from c1 a,c2 b
/*
b01 b02
----- ----------
M03 xx
M04 yy
(2 行受影响)
*/
go
drop table ta,tb
------解决方案--------------------OH,两个0
create table ta(a01 varchar(10))
create table tb(b01 int,b02 varchar(10))
insert into ta select 'M001' union all select 'M002'
insert into tb select 11,'xx' union all select 11,'yy'
go
;with c1 as(
select ROW_NUMBER()Over(order by b02)rn,b02 from tb
),c2 as(
select top 1 convert(int,right(a01,2))id from ta a where not exists(select 1 from ta where a01>a.a01)
)select 'M'+right('000'+ltrim(a.rn+b.id),3)as b01,a.b02 from c1 a,c2 b
/*
b01 b02
------- ----------
M003 xx
M004 yy
(2 行受影响)
*/
go
drop table ta,tb