2014-09-11 87 views
1

我有一个SQL脚本(使用SQL Server 2008):显示最近的日期+唯一的ID

SELECT distinct 
    ServiceIdentifier as ReceivedFrom, EventDate 
FROM 
    [dbo].AttendanceEvent             
WHERE 
    ServiceIdentifier in (5001, 5003, 5004) 

,显示date(柱:EventDate)和组织机构代码(柱:ServiceIdentifier)的每一行中我的桌子(名字:AttendanceEvent)。我使用where serviceidentifier in (x,y,z)子句输入我想查看的特定组织。

这个脚本非常方便,不同之处在于它会将每个单独的记录拉到太多,超出我的SQL时间。

我想优化脚本以只拉取每个组织的最近日期。

给我1行serviceidentifier

EventDate所在的日期格式是; 2014-08-23 19:31:44.163如果这影响什么。

任何帮助和建议非常感谢!

E.H

P.S我通过一些其他的问题,看了,但不能真正告诉我们,如果我的是重复的,如果你认为它是,请让我知道,我会在那里寻找!

回答

2

只需使用group by

SELECT ServiceIdentifier as ReceivedFrom, max(EventDate) as EventDate 
FROM [dbo].AttendanceEvent             
where ServiceIdentifier in (5001, 5003, 5004) 
group by ServiceIdentifier; 
+0

谢谢 - 工作brillantly! :) – user1300011 2014-09-11 05:07:16