sqlserver row_number() over() 理解

 1 -- 创建语句
 2 create table goodsTest(--商品表
 3     id int primary key identity(1,1),
 4     goosType varchar(100),--商品归类
 5     goodsName varchar(100),--商品名称
 6     serialNo int
 7 )
 8 go
 9 insert into goodsTest(goosType,goodsName)
10 select '面类','面包' union
11 select '面类','烩面' union
12 select '饮品','矿泉水' union
13 select '饮品','冰红茶' union
14 select '饮品','' union
15 select '面类','饸烙面' union
16 select '面类','鸡蛋灌饼' union
17 select '面类','手抓饼' union
18 select '饮品','茶π' union
19 select '零食','脆司令' union
20 select '零食','劲仔小鱼' union
21 select '零食','卫龙' 
22 
23 --用法1.》》》row_number() over(Order by ...)
24 select row_number() over(order by goodsName) rownum,goodsName  from goodsTest --根据goodsName 排序得到连续的序号rownum
25 
26 --用法2.》》》row_number() over(partition by ... Order by ...)
27 select row_number() over(partition by goosType order by goodsName) rownum,goodsName  from goodsTest --根据 goosType 分组,goodsName 排序得到连续的序号rownum
28 
29 --经常用法3.》》》 修改数据的序号serialNo
30 update a set serialNo=b.RowNum
31 from  goodsTest a,
32 (select ROW_NUMBER() over(partition by goosType order by goodsName) RowNum,id from goodsTest /*where ID=''*/) b
33 where a.id=b.id 

 

posted @ 2020-12-10 14:53  龙er飞  阅读(1007)  评论(0编辑  收藏  举报