4

我想从 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 的最新记录它应该返回第三条记录(PKID = 3)......如何获得?我写了下面的代码,但它什么也没返回。

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

5 回答 5

3
select top 1 * from tablename where FKID = 25 order by CDateTime desc
于 2012-11-19T12:41:01.857 回答
3

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

 SELECT * from Table1 WHERE FKID = 25
     and CDateTime= (select max(CDateTime) From Table1 where FKID = 25 )
于 2012-11-19T12:41:36.867 回答
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
于 2012-11-19T13:03:21.887 回答
1

您的查询没有返回值,因为子查询(从 Table1 中选择 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
于 2012-11-19T12:42:23.337 回答
0

尝试这个:

SELECT * from Table1 WHERE FKID = 25
and CDateTime= (select max(CDateTime) From Table1 where FKID = 25)
于 2012-11-19T12:41:16.110 回答