emp表记录赞:
列表
id name date
1 ankit 18-12-2014 05:55:22.000
2 mehul 18-12-2014 04:44:22.000
3 vimal 18-12-2014 03:44:22.000
4 ankit 18-12-2014 06:00:22.000
5 mehul 18-12-2014 06:10:22.000
我想输出如下:
4 ankit 18-12-2014 06:00:22.000
5 mehul 18-12-2014 06:10:22.000
3 vimal 18-12-2014 03:44:22.000
插入这样的新记录时:
vimal 18-12-2014 06:30:22.000
然后输出如:
4 ankit 18-12-2014 06:00:22.000
5 mehul 18-12-2014 06:10:22.000
6 vimal 18-12-2014 06:30:22.000
那怎么可能呢?
答案 0 :(得分:2)
使用ROW_NUMBER()
,因为您需要每个用户名一条记录,这将是OVER
子句(PARTITION BY Name
)中的分区字段,然后您需要每个用户名的最新记录,所以这将是您在OVER
子句(ORDER BY Date DESC
)中的订单:
SELECT ID, Name, Date
FROM ( SELECT ID,
Name,
Date,
RowNumber = ROW_NUMBER() OVER(PARTITION BY Name
ORDER BY Date DESC)
FROM T
) AS T
WHERE RowNumber = 1;
答案 1 :(得分:0)
另一种解决方案可能是加入:
select K.*
from (
select X.Name,
max(X.Date) MaxDate
from emp X
) Y
join emp K on K.name = Y.name and K.Date = Y.MaxDate
答案 2 :(得分:0)
N =表的行数
DECLARE @X INT=(SELECT COUNT(*) FROM empt )
SELECT ID,
Name,
Date
FROM empt
ORDER BY ID OFFSET (@X-3) ROWS FETCH NEXT 3 ROWS ONLY;