3

I use SQL Server 2008R2, I need to findout the missing dates.

 ID College  Dept   JoiningDate
  1 SAEC     CSE    1/2/2008
  2 MSEC     EEE    4/2/2008
  3 GOV      ECE    8/2/2008
  4 JKP      CSE    9/2/2008
  5 VLM      CSE    10/2/2008
  6 PTR      CSE    13/2/2008

Output

JoiningDate
2/2/2008
3/2/2008
5/2/2008
6/2/2008
7/2/2008
11/2/2008
12/2/2008
4

2 回答 2

3

我已经在评论中为您提供了相同类型的问题链接,如果您仍然有困惑,您可以检查如下

;with d(date) as (
    select cast('2/1/2008' as datetime)
    union all
    select date+1
    from d
    where date < '2/13/2008'
)

select  d.date CDate
from d
left join CollegeDate t
on t.JoiningDate = d.date
WHERE ID is null 
order by d.date

SQL 小提琴链接

于 2013-04-09T12:45:00.280 回答
0

试试这个脚本,它会在不指定常量的情况下找出缺失的日期 -

DECLARE @CollegeDate TABLE 
(
  College NVARCHAR(10)
, Dept NVARCHAR(10)
, JoiningDate DATETIME
)

INSERT INTO @CollegeDate (College, Dept, JoiningDate)
VALUES 
('SAEC', 'CSE', '2/1/2008'),
('MSEC', 'EEE', '2/4/2008'),
('GOV', 'ECE', '2/8/2008'),
('JKP', 'CSE', '2/9/2008'),
('VLM', 'CSE', '2/10/2008'),
('PTR', 'CSE', '2/13/2008')

;WITH dateout AS 
(
SELECT 
   JoiningDate = MIN(JoiningDate)
 , MaxJoiningDate = MAX(JoiningDate)
FROM @CollegeDate

UNION ALL

SELECT 
   JoiningDate + 1
 , MaxJoiningDate
FROM dateout
WHERE JoiningDate < MaxJoiningDate
)

SELECT d.JoiningDate
FROM dateout d
WHERE d.JoiningDate NOT IN (SELECT c.JoiningDate FROM @CollegeDate c)
ORDER BY d.JoiningDate
于 2013-04-09T13:42:32.957 回答