row_number() over(order by) 与count(1)

2005中的  row_number() over(order by) 给我们带来了什么 例子比较

借用无枪的狙击手 与 昨夜小楼

declare @t table(a char(2),b char(2),c char(2),d char(2))
insert @t select 'a1','b1','c1','d'
insert @t select 'a1','b1','c2','d'
insert @t select 'a1','b1','c3','d'
insert @t select 'a1','b2','c4','d'
insert @t select 'a1','b2','c5','d'
insert @t select 'a2','b3','c6','d'

select a,b,c,
(
select count(1) from @t where a.a = a and a.b = b and c <= a.c) as count
from @t a

/*


a    b    c    count      
---- ---- ---- -----------
a1   b1   c1   1
a1   b1   c2   2
a1   b1   c3   3
a1   b2   c4   1
a1   b2   c5   2
a2   b3   c6   1

(所影响的行数为 6 行)

--原始数据:@TT
declare @TT table(a varchar(2),b varchar(2),c varchar(2),d varchar(1))
insert @TT
select 'a1','b1','c1','d' union all
select 'a1','b1','c2','d' union all
select 'a1','b1','c3','d' union all
select 'a1','b2','c4','d' union all
select 'a1','b2','c5','d' union all
select 'a2','b3','c6','d'

/*
partition by a,b -> 分组
order by c ->分组编号顺序,如果顺序不敏感,可如上例 order by a
*/
select *, id = row_number() over (partition by a,b order by c) from @TT

/*
a    b    c    d    id
---- ---- ---- ---- --------------------
a1   b1   c1   d    1
a1   b1   c2   d    2
a1   b1   c3   d    3
a1   b2   c4   d    1
a1   b2   c5   d    2
a2   b3   c6   d    1

一目了然呵呵

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值