Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 help

Author  Topic 

mani_1234
Starting Member

24 Posts

Posted - 2012-09-25 : 06:57:02
suppose i have input table like this
Emp.No Date
E1 10-Jan-2011
E1 11-Jan-2011
E1 14-Jan-2011
E2 10-Jan-2011
E2 11-Jan-2011
E2 12-Jan-2011
E2 14-Jan-2011

i want the missing date for each of employee ...i thnk the question
is clear ...
i want output as
Emp.no date
E1 12-jan-2011
E1 13-jan-2011
E2 13-Jan-2011

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-09-25 : 07:04:07
Easiest way to do this is using a calendar table. If you don't have one in your database, create one using the code below.
CREATE TABLE #Calendar (Dt DATETIME);

DECLARE @startDate DATETIME, @endDate DATETIME;
SET @startDate = '20110101';
SET @endDate = '20110131';

;WITH cte AS
(
SELECT @startDate AS Dt
UNION ALL
SELECT DATEADD(dd,1,dt) FROM cte
WHERE dt < @endDate
)
INSERT INTO #Calendar SELECT Dt FROM cte;
Then join the calendar table like shown below.
;WITH e AS 
(
SELECT DISTINCT EmpNo FROM YourTable
)
SELECT
e.EmpNo,
c.Dt
FROM
e
CROSS JOIN #Calendar c
LEFT JOIN YourTable y ON y.EmpNo = e.EmpNo AND y.Dt = c.Dt
WHERE
y.Dt IS NULL;
Go to Top of Page
   

- Advertisement -