-3

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

例如(2010 年 1 月 1 日和 2011 年 1 月 1 日)

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
4

2 回答 2

1

首先你的逻辑不确定。现在试试这个。这是小提琴的例子

;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
于 2012-12-21T15:12:59.063 回答
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
                      )
               )
于 2012-12-21T15:12:10.497 回答