日期:2014-05-18  浏览次数:20446 次

实现组内自动编号
请问sql组内编号怎么写,比如数据如下  
组名 成员  
一组 a  
一组 b  
二组 c  
二组 d  
期望结果:  
组名 成员 编号  
一组 a 1  
一组 b 2  
二组 c 1  
二组 d 2  
实现组内自动编号,如何实现?

------解决方案--------------------
方法有很多种啊,你想写在DB里啊?写在外面往里面存不好吗?
------解决方案--------------------
SQL code
CREATE TABLE TB ([组名] NVARCHAR(32), [成员] VARCHAR(12))
INSERT TB SELECT  '一组','a' UNION ALL  
SELECT  '一组','b' UNION ALL 
SELECT  '二组','c' UNION ALL   
SELECT  '二组','d'

select *,
编号=row_number() over (partition by 组名 order by 组名)
from TB
/*
组名    成员    编号
二组    c    1
二组    d    2
一组    a    1
一组    b    2
*/

------解决方案--------------------
CREATE TABLE TB ([组名] NVARCHAR(32), [成员] VARCHAR(12))
INSERT TB SELECT '一组','a' UNION ALL
SELECT '一组','b' UNION ALL 
SELECT '二组','c' UNION ALL
SELECT '二组','d'

SELECT *,ROW_NUMBER() OVER(PARTITION BY [组名] ORDER BY [组名] DESC) NUM FROM TB
------解决方案--------------------
这样?
SQL code
--> --> (Roy)生成測試數據
 
if not object_id('Tempdb..#T') is null
    drop table #T
Go
Create table #T([组名] nvarchar(2),[成员] nvarchar(1))
Insert #T
select N'一组',N'a' union all
select N'一组',N'b' union all
select N'二组',N'c' union all
select N'二组',N'd'
Go
alter table #T add 编号 int --新增字段
--
go
update t1
set 编号=编号2
from (select *,
编号2=ROW_NUMBER()OVER (partition by 组名 order by 组名)
from #T
)t1
go
select * from #T

/*
组名    成员    编号
一组    a    1
一组    b    2
二组    c    1
二组    d    2
*/

------解决方案--------------------
SQL code

--> 测试数据:[tbl]
if object_id('[tbl]') is not null drop table [tbl]
create table [tbl]([组名] varchar(4),[成员] varchar(1))
insert [tbl]
select '一组','a' union all
select '一组','a' union all
select '一组','b' union all
select '一组','b' union all
select '二组','c' union all
select '二组','d'
--2000中的方法:
go
alter table tbl add id int
go
alter table tbl add row int identity(1,1)
go
update tbl set id=row_num from(
select *,
row_num=(select COUNT(1) from tbl where 组名=a.组名 and 成员=a.成员 and row<=a.row)
from tbl as a)b where tbl.row=b.row
go
alter table tbl drop column row
go
select * from tbl
--2005以上版本的方法:
go
alter table tbl add row int identity(1,1)--增加标识列,用来更新时确定一一对应
go
;with t 
as(
select s=ROW_NUMBER()over(partition by [组名],[成员] order by getdate()),
* from tbl
)
update tbl set tbl.id=t.s from t
where t.row=tbl.row
go
alter table tbl drop column row
select * from tbl
/*
组名    成员    id
一组    a    1
一组    a    2
一组    b    1
一组    b    2
二组    c    1
二组    d    1
*/