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

按组分类赋值
请问sql组内编号怎么写,比如数据如下 
组名 成员 
一组 a 
一组 b 
二组 c 
二组 d 
期望结果: 
组名 成员 编号 
一组 a 1 
一组 b 2 
二组 c 1 
二组 d 2 
实现组内编号这样的sql应该怎么写?

------解决方案--------------------
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'

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
/*
组名    成员    id
一组    a    1
一组    a    2
一组    b    1
一组    b    2
二组    c    1
二组    d    1
*/

--楼主的结果是不是给错了?

------解决方案--------------------
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
*/