如何获得具有相同ID的最新记录?

时间:2012-11-19 12:38:30

标签: 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     2012-11-19 17:56:22.000

现在,我想要有FKID 25的最新记录它应该返回第3条记录(PKID = 3) ......怎么做到的? 我写了下面的代码,但它没有返回任何内容。

SELECT * from Table1 WHERE FKID = 25
 and CDateTime= (select max(CDateTime) From Table1 )

5 个答案:

答案 0 :(得分:3)

select top 1 * from tablename where FKID = 25 order by CDateTime desc

答案 1 :(得分:2)

你遇到的问题是你提出的AND约束永远不会成立,因此你没有获得任何输出。 这个查询可以解决问题。

 SELECT * from Table1 WHERE FKID = 25
     and CDateTime= (select max(CDateTime) From Table1 where FKID = 25 )

答案 2 :(得分:2)

此问题的另一个解决方案是加入一个子查询,该子查询获得每个FKID的最新日期。

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT FKID, MAX(CDATETIME) maxDate
            FROM tableName
            GROUP BY FKID
        ) b ON a.FKID = b.FKID AND
                a.CDateTime = MaxDate

或使用Common Table Expression

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

答案 3 :(得分:1)

您的查询未返回值,因为子查询(从表1中选择max(CDateTime)) 将为您提供整个表中的最大CDateTime,而不是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

答案 4 :(得分:0)

试试这个:

SELECT * from Table1 WHERE FKID = 25
and CDateTime= (select max(CDateTime) From Table1 where FKID = 25)