DECLARE @MyTable TABLE
(
ID INT IDENTITY PRIMARY KEY,
[Date] SMALLDATETIME NOT NULL,
WorkingTime INT NOT NULL,
EmployeeID INT NOT NULL
);
INSERT @MyTable ([Date], WorkingTime, EmployeeID)
-- First employee
SELECT '20130801', 1, 123 UNION ALL
SELECT '20130802', 0, 123 UNION ALL
SELECT '20130803', 0, 123 UNION ALL
SELECT '20130804', 1, 123 UNION ALL
SELECT '20130805', 1, 123 UNION ALL
SELECT '20130806', 1, 123 UNION ALL
SELECT '20130807', 1, 123 UNION ALL
SELECT '20130808', 1, 123 UNION ALL
SELECT '20130809', 0, 123 UNION ALL
SELECT '20130810', 1, 123 UNION ALL
-- Second employee
SELECT '20130801', 1, 126 UNION ALL
SELECT '20130802', 1, 126 UNION ALL
SELECT '20130803', 1, 126 UNION ALL
SELECT '20130804', 1, 126 UNION ALL
SELECT '20130805', 1, 126 UNION ALL
SELECT '20130806', 0, 126 UNION ALL
-- Third employee
SELECT '20130801', 0, 127 UNION ALL
SELECT '20130802', 0, 127 UNION ALL
SELECT '20130803', 1, 127 UNION ALL
SELECT '20130804', 1, 127 UNION ALL
SELECT '20130805', 0, 127 UNION ALL
SELECT '20130806', 0, 127;
-
DECLARE @Results TABLE
(
EmployeeID INT NOT NULL,
DaysDiff INT NOT NULL,
PRIMARY KEY(EmployeeID, DaysDiff), -- This is a "clustered index"/index organized table
RowNum INT IDENTITY NOT NULL,
[Date] SMALLDATETIME NOT NULL
);
INSERT @Results (EmployeeID, DaysDiff, [Date])
SELECT x.EmployeeID,
DATEDIFF(DAY, 0, x.[Date]) AS DaysDiff,
x.[Date]
FROM @MyTable x
WHERE x.WorkingTime = 1
/*
This ORDER BY clause and the clustered index (PRIMARY KEY(EmployeeID, DaysDiff))
should give a hint to SQL Server so that
RowNum IDENTITY values will be generated in this order: EmployeeID, DaysDiff
Note #1: There is not 100% guarantee that insert order will be the same as
ORDER BY x.EmployeeID, DaysDiff
and
clustered index key (EmployeeID, DaysDiff)
Note #2: This INSERT INTO table with identity column simulates the ROW_NUMBER function
which is available starting with SQL2005.
*/
ORDER BY x.EmployeeID, DaysDiff
OPTION (MAXDOP 1); -- It minimizes the risk of messing up the order of RowNum
SELECT y.EmployeeID, MAX(y.GroupStartDate) AS FirstGroupStartDate
FROM
(
SELECT x.EmployeeID, x.GroupID,
MIN(x.[Date]) AS GroupStartDate, MAX(x.[Date]) AS GroupEndDate,
DATEDIFF(DAY, MIN(x.[Date]), MAX(x.[Date]))+1 AS ContinuousDays
FROM
(
SELECT *, r.DaysDiff - r.RowNum AS GroupID
FROM @Results r
) x
GROUP BY x.EmployeeID, x.GroupID
) y
WHERE y.ContinuousDays > 4
GROUP BY y.EmployeeID;
真的使用SQL Server 2000? :( –
尋找一個WorkingTime = 5的總和可能是解決方案的一部分 –
@Goat CO,告訴我一下吧 – mameesh