sql找到最近的记录

时间:2012-08-13 13:13:02

标签: sql

我有以下查询,它获取具有给定条件的记录计数。以下显示了表中的两条记录和查询结果。我想要的是根据EntryDate列获取最新的事件。

0 A 2012-08-09 00:00:00.000 N0206527 N0168639 NULL 09 420202 LTD False  
0 A 2012-08-08 00:00:00.000 N0206527 N0168639 NULL 09 420202 LTD False

DCMNumber CustomerDivision CustomerSerial Product PriorNonDenied    
N0064819  09               420202     LTD     2


SET @firstDayOfCurrentMonth = DATEADD(m,DATEDIFF(M,0,GETDATE()),0)
SELECT  DCMNumber, CustomerDivision, CustomerSerial, Product, COUNT(*) AS PriorNonDenied
                             FROM   cauAssignedClaim 
                             WHERE  RecordType = 'A' AND  
                                   EscFromSTD = '0' AND  
                                   ([Status] <> 'DE' OR  
                                    [Status] IS NULL) AND  
                                   CONVERT(VARCHAR(10), EntryDate, 110) BETWEEN  
                                       CASE WHEN Product = 'LTD' THEN   CONVERT(VARCHAR(10), @firstDayOfCurrentMonth, 110)    
                                       ELSE CONVERT(VARCHAR(10), DATEADD(Day, -7, GETDATE()-1), 110)  
                                       END  
                                       AND CONVERT(VARCHAR(10), GETDATE()-1, 110) 
                             GROUP BY [Status],  
                                      DCMNumber,  
                                      CustomerDivision,  
                                      CustomerSerial,  
                                      Product  

谢谢, 布拉德

3 个答案:

答案 0 :(得分:4)

我想你想要这样的东西

SELECT a.EntryDate, a.DCMNumber, CustomerDivision, CustomerSerial, Product, WhateverElse, etc
FROM cauAssignedClaim b INNER JOIN

(SELECT MAX(DCMNumber) DCMNumber, MAX(EntryDate) EntryDate
FROM cauAssignedClaim
GROUP BY DCMNumber) a

ON ( a.DCMNumber = b.DCMNumber AND a.EntryDate = b.EntryDate )

这将为您提供所有唯一DCMNumber及其最新日期的列表。然后,您可以使用所需的所有其他数据加入该数据。最终结果将返回每个DCMNumber的最新信息。

如果这不是您想要的,请添加更多详细信息,以便我们更好地了解您的目标。

答案 1 :(得分:1)

MySQL的:

SELECT * FROM table ORDER BY EntryDate DESC LIMIT 1

MSSQL:

SELECT TOP 1 * FROM ORDER BY EntryDate DESC

答案 2 :(得分:1)

试试这个

Select Top 1 col1 From Table Order by MyDate DESC