如何在SQL Server中获得第一个和最后一个出勤系统

时间:2014-08-29 09:02:03

标签: sql-server sql-server-2008 tsql sql-server-2005

我有一张表IOData,如下所示

   E Name   Date            Time    Status
   A1   08/06/14    19:36:10.00 Entry
   A1   08/06/14    19:36:16.00 Exit
   A1   08/06/14    19:36:18.00 Entry
   A1   08/07/14    00:26:39.00 Exit
   A1   08/07/14    00:38:36.00 Entry
   A1   08/07/14    02:41:14.00 Exit
   B1   08/07/14    19:12:29.00 Entry
   B1   08/08/14    04:14:28.00 Exit
   B1   08/08/14    04:14:31.00 Entry
   B1   08/08/14    04:14:33.00 Exit
   C1   08/06/14    19:26:10.00 Entry
   C1   08/06/14    19:36:16.00 Exit
   C1   08/06/14    19:36:50.00 Entry
   C1   08/06/14    23:06:28.00 Exit

我希望输出为第一个Entry和Last Exit,如下所示

 EName    Date        Time      Status
   A1    08/06/14   19:36:10.00 Entry
   A1    08/07/14   02:41:14.00 Exit
   B1    08/07/14   19:12:29.00 Entry
   B1    08/08/14   04:14:33.00 Exit
   C1    08/06/14   19:26:10.00 Entry
   C1    08/06/14   23:06:28.00 Exit

我无意执行此任务。我用谷歌搜索但没有帮助。请做好。

提前致谢

2 个答案:

答案 0 :(得分:0)

;WITH MyCTE AS
(
    SELECT EName,
           Date,
           Time,
           Status,
           ROW_NUMBER() OVER(PARTITION BY EName ORDER BY Date, Time) AS FirstRn,
           ROW_NUMBER() OVER(PARTITION BY EName ORDER BY Date DESC, Time DESC) AS LastRn
    FROM   IOData 
)
SELECT   EName,
         Date,
         Time,
         Status
FROM     MyCTE  
WHERE    FirstRn = 1 
         OR LastRn = 1
ORDER BY EName,
         Date,
         Time

<强> SQL Fiddle DEMO

答案 1 :(得分:0)

DECLARE @IOData AS TABLE(Name VARCHAR(MAX), [Date] DATE, [Time] TIME, [Status] VARCHAR(MAX)) INSERT INTO @IOData(Name, [Date], [Time], [Status]) VALUES ('A1', '08/06/14', '19:36:10.00', 'Entry'), ('A1', '08/06/14', '19:36:16.00', 'Exit'), ('A1', '08/06/14', '19:36:18.00', 'Entry'), ('A1', '08/07/14', '00:26:39.00', 'Exit'), ('A1', '08/07/14', '00:38:36.00', 'Entry'), ('A1', '08/07/14', '02:41:14.00', 'Exit'), ('B1', '08/07/14', '19:12:29.00', 'Entry'), ('B1', '08/08/14', '04:14:28.00', 'Exit'), ('B1', '08/08/14', '04:14:31.00', 'Entry'), ('B1', '08/08/14', '04:14:33.00', 'Exit'), ('C1', '08/06/14', '19:26:10.00', 'Entry'), ('C1', '08/06/14', '19:36:16.00', 'Exit'), ('C1', '08/06/14', '19:36:50.00', 'Entry'), ('C1', '08/06/14', '23:06:28.00', 'Exit')

;WITH _FirstEntries AS ( SELECT DISTINCT FirstEntries.* FROM @IOData AS ID OUTER APPLY (SELECT TOP 1 * FROM @IOData AS ID2 WHERE [Status] = 'Entry' AND ID2.Name = ID.Name ORDER BY ID2.[Date] ASC , ID2.[Time] ASC) AS FirstEntries ) , _LastExits AS( SELECT DISTINCT LastExit.* FROM @IOData AS ID OUTER APPLY (SELECT TOP 1 * FROM @IOData AS ID2 WHERE [Status] = 'Exit' AND ID2.Name = ID.Name ORDER BY ID2.[Date] DESC , ID2.[Time] DESC) AS LastExit )
SELECT * FROM ( SELECT * FROM _FirstEntries UNION ALL
SELECT * FROM _LastExits ) AS ResultUnSorted ORDER BY Name, [Status]