如何从SQL Server数据库c#获取最新/最新记录?

时间:2011-03-17 22:29:18

标签: c# sql sql-server

在我的发言中:

SELECT
    MonitoringJob.ID,
    MonitoringJob.CreationDate,
    MonitoringJob.LastCheck, 
    MonitoringJob.Category,
    MonitoringJob.URL,
    MonitoringJob.Description,
    MonitoringJob.IsJobActive,
    History.ChangeDateTime
FROM  MonitoringJob
INNER JOIN History
ON MonitoringJob.ID=History.JobID
ORDER BY History.ChangeDateTime DESC

我从数据库获取:

7244D096-D388-4216-AE9D-8556F342F0F1    2011-03-17 22:47:15.007 2011-03-17 22:52:28.040 test2   www.spiegel.de  test2   1   2011-03-17 22:52:28.040
6152F7E6-5C4B-42B5-B05B-D3EC43E4B56F    2011-03-17 22:46:59.137 2011-03-17 22:52:27.507 test1   www.ragims.de   test1   1   2011-03-17 22:52:27.507
7244D096-D388-4216-AE9D-8556F342F0F1    2011-03-17 22:47:15.007 2011-03-17 22:52:28.040 test2   www.spiegel.de  test2   1   2011-03-17 22:51:28.323
6152F7E6-5C4B-42B5-B05B-D3EC43E4B56F    2011-03-17 22:46:59.137 2011-03-17 22:52:27.507 test1   www.ragims.de   test1   1   2011-03-17 22:49:27.413

我想获得CheckDateTime的最新值,它是数据库中的最后一列。 我只需要:

7244D096-D388-4216-AE9D-8556F342F0F1    2011-03-17 22:47:15.007 2011-03-17 22:52:28.040 test2   www.spiegel.de  test2   1   2011-03-17 22:52:28.040
    6152F7E6-5C4B-42B5-B05B-D3EC43E4B56F    2011-03-17 22:46:59.137 2011-03-17 22:52:27.507 test1   www.ragims.de   test1   1   2011-03-17 22:52:27.507

ORDER BY History.ChangeDateTime DESC为我提供了按日期时间排序的值,我需要一些不同的代码片段。请帮忙!

4 个答案:

答案 0 :(得分:7)

这应该有效

SELECT    MAX(History.ChangeDateTime)
FROM  MonitoringJob
INNER JOIN History
ON MonitoringJob.ID=History.JobID
GROUP BY MonitoringJob.ID

答案 1 :(得分:1)

您是否想要具有最新值的行?

SELECT    * -- 
FROM  MonitoringJob
INNER JOIN History
ON MonitoringJob.ID=History.JobID
WHERE CAST(ChangeDateTime as DATE) = (SELECT CAST(MAX(ChangeDateTime) as DATE) FROM History)

这将为您提供日期与最高ChangeDateTime 日期相同的所有记录。

答案 2 :(得分:1)

答案 3 :(得分:0)

您将需要执行groupBy语句(无论test2,test1列是什么),然后调用orderBy CheckDatTime desc并使用select TOP(1)命令完成它。使用groupBy命令,您只能返回子句中指定的列,因此如果您需要更多信息,则可能需要在该表上执行自联接操作。