读书人

实现组内自动编号,该如何解决

发布时间: 2012-04-20 15:27:03 作者: rapoo

实现组内自动编号
请问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 #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*/
[解决办法]
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'--2000中的方法: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--2005以上版本的方法:goalter 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 twhere t.row=tbl.rowgoalter table tbl drop column rowselect * from tbl/*组名    成员    id一组    a    1一组    a    2一组    b    1一组    b    2二组    c    1二组    d    1*/ 

读书人网 >SQL Server

热点推荐