Sql 如何获取具有相同ID的最新记录?
我想从SQL数据表中获取最新记录。 我有下面的数据表。 但是它返回了0个记录 表1Sql 如何获取具有相同ID的最新记录?,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我想从SQL数据表中获取最新记录。 我有下面的数据表。 但是它返回了0个记录 表1 PKID----FKID-----------CDateTime 1 25 2012-11-19 17:51:22.000 2 25 2012-11-19 17:53:22.000 3 25 2012-11-19 17:54:22.000 4 26 2012-11-19 17:55:22.000 5 26
PKID----FKID-----------CDateTime
1 25 2012-11-19 17:51:22.000
2 25 2012-11-19 17:53:22.000
3 25 2012-11-19 17:54:22.000
4 26 2012-11-19 17:55:22.000
5 26 2012-11-19 17:56:22.000
现在,我想要fkid25的最新记录,它应该返回第三条记录PKID=3
…怎么才能得到呢?
我已经写了下面的代码,但它没有返回任何内容
SELECT * from Table1 WHERE FKID = 25
and CDateTime= (select max(CDateTime) From Table1 )
试试这个:
SELECT * from Table1 WHERE FKID = 25
and CDateTime= (select max(CDateTime) From Table1 where FKID = 25)
with cte as(
SELECT *,row_number() over (partition by FKID order by CDateTime desc) as rn
from Table1 )
select * from cte
WHERE FKID = 25
and rn=1
您的问题是,您正在放置一个永远不会为真的AND约束,因此无法获得任何输出。 这个查询就可以了
SELECT * from Table1 WHERE FKID = 25
and CDateTime= (select max(CDateTime) From Table1 where FKID = 25 )
您的查询没有返回值,因为子查询从表1中选择maxCDateTime 将为您提供整张表中的最大CDateTime(不适用于FKID=25) 试试这个:
SELECT * from Table1 WHERE FKID = 25
and CDateTime= (select max(CDateTime) From Table1 where FKID = 25)
with cte as(
SELECT *,row_number() over (partition by FKID order by CDateTime desc) as rn
from Table1 )
select * from cte
WHERE FKID = 25
and rn=1
此问题的另一个解决方案是在子查询上加入自身,该子查询获取每个FKID的最新日期 或者使用公共表表达式
TOP1是什么意思?
WITH latestRecords
AS
(
SELECT PKID, FKID, CDATETime,
ROW_NUMBER() OVER (PARTITION BY FKID
ORDER BY CDateTime DESC) rn
FROM TableNAme
)
SELECT PKID, FKID, CDATETime
FROM latestRecords
WHERE rn = 1