2016-08-24 55 views

回答

2

使用Row_Number()窗口功能

With cte as 
(
select *,Row_Number()over(order by Transdate desc) as Rn from yourtable 
Where DriverID = 134 
) 
Select * 
from cte 
Where Rn = 2 

要处理的时候,只有一个纪录为给DriverID然后使用这个

With cte as 
(
select *,Row_Number()over(order by Transdate desc) as Rn, 
count(1)over() as cnt from yourtable 
Where DriverID = 134 
) 
Select * 
from cte 
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1) 

注:如果在最后一秒记录领带和你想同时记录然后使用DENSE_RANK代替ROW_NUMBER

更新:

要查找的倒数第二个记录为全部DriverID'sRow_number中添加分区并从Where子句中删除DriverID子句

With cte as 
(
select *,Row_Number()over(Partition by DriverID order by Transdate desc) as Rn, 
count(1)over(Partition by DriverID) as cnt from yourtable 
) 
Select * 
from cte 
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1) 
+0

你是比我快... +1但是:你可以使用<= 2搭上情况下,只有一个记录......(取决于课程的现实需要) 。 – Shnugo

+0

@Shnugo - 是的,你是对的。相应地更新了答案。我们不能使用<= 2,因为它会拉动两条记录,当你有超过1条记录给定'DriverID' –

+0

你能帮我怎么从我的表中填充数据每秒排序最后一条记录多一个driverid –

0
SELECT * FROM (
    SELECT 
ROW_NUMBER() OVER (ORDER BY key DEC) AS rownumber, 
columns 
FROM tablename 
) AS foo 
WHERE rownumber <= 2