首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

按组分类赋值,该如何解决

2012-04-19 
按组分类赋值请问sql组内编号怎么写,比如数据如下组名成员一组a一组b二组c二组d期望结果:组名成员编号一组

按组分类赋值
请问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 allselect '一组','a' union allselect '一组','b' union allselect '一组','b' union allselect '二组','c' union allselect '二组','d'goalter table tbl add id intgoalter table tbl add row int identity(1,1)goupdate 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.rowgoalter table tbl drop column rowgoselect * 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 #TGoCreate table #T([组名] nvarchar(2),[成员] nvarchar(1))Insert #Tselect N'一组',N'a' union allselect N'一组',N'b' union allselect N'二组',N'c' union allselect N'二组',N'd'Goalter table #T add 编号 int --新增字段--goupdate t1set 编号=编号2from (select *,编号2=ROW_NUMBER()OVER (partition by 组名 order by 组名)from #T)t1goselect * from #T/*组名    成员    编号一组    a    1一组    b    2二组    c    1二组    d    2*/ 

热点排行