日期:2014-05-18 浏览次数:20772 次
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([ID] INT,[billid] INT,[aid] int) INSERT [tb] SELECT 1,1000,NULL UNION ALL SELECT 2,1000,NULL UNION ALL SELECT 3,1000,NULL UNION ALL SELECT 4,1001,NULL UNION ALL SELECT 5,1001,NULL UNION ALL SELECT 6,1001,NULL UNION ALL SELECT 7,1001,NULL UNION ALL SELECT 8,1001,NULL GO --> 测试语句: ;with t as ( SELECT *,row_id=row_number() over(partition by billid order by id) FROM [tb] ) update t set aid=row_id select * from tb /* ID billid aid ----------- ----------- ----------- 1 1000 1 2 1000 2 3 1000 3 4 1001 1 5 1001 2 6 1001 3 7 1001 4 8 1001 5 (8 行受影响) */
------解决方案--------------------
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([ID] INT,[billid] INT,[aid] int) INSERT [tb] SELECT 1,1000,NULL UNION ALL SELECT 2,1000,NULL UNION ALL SELECT 3,1000,NULL UNION ALL SELECT 4,1001,NULL UNION ALL SELECT 5,1001,NULL UNION ALL SELECT 6,1001,NULL UNION ALL SELECT 7,1001,NULL UNION ALL SELECT 8,1001,NULL GO --> 2000: update t set t.aid=(select count(*) from tb where billid=t.billid and id<=t.id) from tb t select * from tb /* ID billid aid ----------- ----------- ----------- 1 1000 1 2 1000 2 3 1000 3 4 1001 1 5 1001 2 6 1001 3 7 1001 4 8 1001 5 (8 行受影响) */
------解决方案--------------------
用开窗函数
select ID billid,
row_number()over(partition by billid order by id) as aid
from table
--------------------------------------------
ID billid aid
1 1000 1
2 1000 2
3 1000 3
4 1001 1
5 1001 2
6 1001 3
7 1001 4
8 1001 5
这个很方便而且灵活,希望对你有所帮助:)