从查询中获取的结果集中查找缺少的月份

时间:2015-03-11 16:14:07

标签: sql-server

我有一组从myTable返回的结果,如下所示

2011-05-02 00:00:00.000 
2011-08-01 00:00:00.000
2011-09-01 00:00:00.000
2011-10-03 00:00:00.000
2011-11-01 00:00:00.000
2011-12-01 00:00:00.000

我想编写一个返回2的查询,因为结果集中缺少2个月。所以我可以引发错误来破解代码。

如果数据集看起来像这样

        2011-05-02 00:00:00.000
        2011-05-02 00:00:00.000
        2011-05-02 00:00:00.000
        2011-05-02 00:00:00.000          
        2011-08-01 00:00:00.000
        2011-08-01 00:00:00.000 
        2011-08-01 00:00:00.000
        2011-08-01 00:00:00.000

再次返回2,因为缺少2个月

1 个答案:

答案 0 :(得分:2)

declare @min date
declare @max date

select @min = min(date_col), @max = max(date_col)
from tbl

;with cte as (
  select distinct m = month(date_col), y = year(date_col)
  from tbl
)
, cal as (
  select m = month(d), y = year(d)
  from (
    select d = dateadd(m, row_number() over(order by (select 1)) - 1, @min)
    from master.dbo.spt_values
  ) t
  where d <= @max
)

select count(1)
from cal
where not exists(
  select 1
  from cte
  where cte.m = cal.m
  and cte.y = cal.y
)

SQL Fiddle

相关问题