按条件在SQL Server中查找缺少的行

时间:2012-12-21 15:02:48

标签: sql sql-server

我试图找出两个参数化日期之间不存在哪些行。

例如(01/01/2010和01/01/2011)

ID      Date    col 3   col 4
123     01/01/2010  x   x
456     01/01/2010  x   x
6578    01/01/2010  x   x
123     01/03/2010  x   x
456     01/03/2010  x   x
6578        01/03/2010  x   x
123     01/01/2011  x   x
456     01/01/2011  x   x
789     01/01/2011  x   x
123     01/01/2012  x   x
456     01/01/2012  x   x
789     01/01/2012  x   x

我想回复:

ID      Date    col 3   col 4
6578    01/01/2010  x   x
789     01/01/2011  x   x

所以在伪代码中

If Id exists for 01/01/2010 but not 01/01/2011, return result
AND
If Id exists for 01/01/2011 but not 01/01/2010, return result

2 个答案:

答案 0 :(得分:1)

首先你的逻辑不确定。现在试试吧。这是fiddle example

;with cte as
(
  select id 
  from t
  group by id
  having count(id) = 1
)
select t.id, t.date, t.col3, t.col4
from t join cte on t.id = cte.id

--Results
ID      DATE           COL3 COL4
789     2011-01-01      x   x
6578    2010-01-01      x   x

答案 1 :(得分:0)

如果您要查找仅出现一次的行,那么这将有效:

select *
from (select t.*,
             count(*) over (partition by id) as NumYears
      from t
     ) t
where NumYears = 1

也许更一般的形式是:

select *
from t
where t.id in (select id
               from t
               group by id
               having (max(case when year(date) = 2010 then 1 else 0 end) = 1 and
                       max(case when year(date) = 2011 then 1 else 0 end) = 0
                      ) or
                      (max(case when year(date) = 2010 then 1 else 0 end) = 0 and
                       max(case when year(date) = 2011 then 1 else 0 end) = 1
                      )
               )