首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

row_number解决方案

2012-03-15 
row_number求row_number这个函数一般用在什么情况下,谢谢[解决办法]一般在分页的时候,或者是返回特定行数

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

/*
pidtimetemp
12012-10-07 00:00:00.00038.0
22012-10-05 00:00:00.00037.5
*/

来一个例子



[解决办法]
额上的例子也举了,概念也讲了,楼主可以参考下了。

热点排行
Bad Request.