Hi - I'm having issues selecting duplicate records from a specific date using a group by / having.
select * from [dbo].[entrytable]
WHERE (CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, entrytime))) = CONVERT(DateTime, DATEDIFF(DAY, 2, GETDATE())))
and stat != 'allowed' and staffnumber
IN (SELECT staffnumber
FROM entrytable
GROUP BY staffnumber
HAVING COUNT(staffnumber ) > 1)
As you can see the select should be selecting records from 2 days before today which works fine but the group by seams to be grouping all records irrespective of the date.
Try casting your date columns in the criteria as date. (Only SQL Server 2008 +)
SELECT
*
FROM
[dbo].[entrytable]
WHERE
Cast(entrytime AS date) = Convert(date, DateDiff(DAY, 2, GetDate())) )
AND stat != 'allowed'
AND staffnumber IN ( SELECT
staffnumber
FROM
entrytable
GROUP BY
staffnumber
HAVING
Count(staffnumber) > 1 );
select *
from dbo.entrytable
WHERE entrytime >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 2, 0)
and entrytime < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 1, 0)
and stat != 'allowed' and staffnumber
IN (SELECT staffnumber
FROM entrytable
GROUP BY staffnumber, DATEADD(DAY, DATEDIFF(DAY, 0, entrytime), 0)
HAVING COUNT(*) > 1)
This took an over 2 mins to run and did not show the number is desired record as set by the count so for example if I set the count(*) to > 3 then it still included records outside of the date
select *
from dbo.entrytable
WHERE entrytime >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 2, 0)
and entrytime < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 1, 0)
and stat <> 'allowed'
and staffnumber IN (SELECT staffnumber
FROM entrytable
WHERE entrytime >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 2, 0)
and entrytime < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 1, 0)
GROUP BY staffnumber
HAVING COUNT(*) > 1);