sql查询根据创建的日期获取不同的记录

时间:2011-03-04 10:09:26

标签: sql sql-server-2008

enter image description here

我在图片中有一些记录。我想编写一个sql查询来获取最新的唯一记录,这样我就只有两个基于UserAlertTicketID和最新创建日期的记录。在这种情况下,输出将如下:

“CB23C56F-B067-415E-AD62-59DF4DA4F26D”“2”“2011-03-04 09:49:59.440”“9EDB3DBC-4685-414D-A48B-04CA8285A2D1”

“9FA4D72B-8BB3-4CE9-BCA2-C334AF47EB30”“3”“2011-03-04 09:05:46.817”“94C67A9C-3818-4AB5-A6F6-CD7BD69FAEC7”

请帮助!!!

由于

2 个答案:

答案 0 :(得分:1)

SELECT TOP 2 * FROM table GROUP BY UserAlertTicketID ORDER BY CreatedDate DESC

编辑:这可能不会做你想要的,但试试这个:

SELECT TOP 2 T1.* FROM Table T1 LEFT JOIN Table T2 
ON (T1.AlertTicketEventID = T2.AlertTicketEventID AND T1.CreatedDate < T2.CreatedDate) 
WHERE T2.AlertTicketEventID IS NULL ORDER BY T1.CreatedDate DESC

此方法将避免使用聚合,并且应该更快。

答案 1 :(得分:0)

这样的东西?

SELECT
a.AlertTicketEventId,
a.AlertTicketStatusID,
a.CreatedDate,
a.UserAlertTicketID 
FROM <Table> a 
INNER JOIN (
    SELECT
     AlertTicketStatusID 
    ,MAX(CreatedDate) AS LastDate
FROM <Table>
GROUP BY AlertTicketStatusID
) b ON a.AlertTicketStatusID = b.AlertTicketStatusID AND a.CreatedDate = b.CreatedDate