I have a table columns Id and EmployeeID. The table data has the following peculiarity: in some parts (where the Id is consecutive), the same EmployeeID can sometimes be found, for example
Id | EmployeeID
---------------
1 | 1
2 | 1
3 | 2
4 | 5
5 | 1
6 | 1
I want to build a query to find blocks of data containing the same EmployeeID where the Id is consecutive (with a minimum value of x records). So far I came up with:
SELECT EmployeeID, MIN(Id), MAX(Id), COUNT(*)
FROM recs
GROUP BY EmployeeID
HAVING COUNT(*) > 5 AND
MAX(Id) - MIN(Id) + 1 = COUNT(*)
This query will bring me some (but not all) blocks of data, as long as the same Employee can only be found in a single block. Can anyone come up with a solution which will provide all different blocks of data for each employee?
Not the best solution, but it should work (for example, 3 consecutive ids):
I suggested that Id is a primary(or a unique) key. If it’s not, you should change a little each of sub-queries to something like SELECT IF(COUNT(1) >0,1,0) …..