日期:2014-05-18  浏览次数:20365 次

row_number
求row_number这个函数一般用在什么情况下,谢谢

------解决方案--------------------
一般在分页的时候,或者是返回特定行数据的时候用 

select row_number() over(order by colmun) from table
------解决方案--------------------
涉及到排序来处理一些问题的时候都可以用row_number,当然要SQL 2005或其以上版本。
------解决方案--------------------
/*
表a 
id time temp pid
1 2012-10-02 37 1
2 2012-10-03 36 2
3 2012-10-04 39 1
4 2012-10-05 37.5 2
5 2012-10-07 38 1

表b
pid name
2 dd
1 aa

结果希望是这样的:
pid time temp
1 2012-10-07 38
2 2012-10-05 37.5

需求:
查询出来的是根据表B有几个PID,
就有几条记录,分别是表A对应
的PID的时间的最大的一条,

在线等,急急急!!!!!
*/

go
if OBJECT_ID('tbla')is not null
drop table tbla
go
create table tbla(
id int,
[time] datetime,
temp numeric(5,1),
pid int
)
go
if OBJECT_ID('tblb')is not null
drop table tblb
go
create table tblb(
pid int,
[name] nvarchar(10)
)

go
insert into tbla(id,[time],temp,pid) values('1','2012-10-02',37,1)
insert into tbla(id,[time],temp,pid) values('2','2012-10-03',36,2)
insert into tbla(id,[time],temp,pid) values('3','2012-10-04',39,1)
insert into tbla(id,[time],temp,pid) values('4','2012-10-05',37.5,2)
insert into tbla(id,[time],temp,pid) values('5','2012-10-07',38,1)

insert into tblb(pid,[name]) values(2,'dd')
insert into tblb(pid,[name]) values(1,'aa')


select tblb.pid,d.time,d.temp
from
(
select c.pid,c.[time],c.temp from
(select ROW_NUMBER()OVER(partition by pid order by [time] desc) as num,* from tbla)c
where num =1
)d inner join tblb on d.pid=tblb.pid

/*
pid time temp
1 2012-10-07 00:00:00.000 38.0
2 2012-10-05 00:00:00.000 37.5
*/

来一个例子



------解决方案--------------------
额上的例子也举了,概念也讲了,楼主可以参考下了。