2012-12-21 46 views
-3

我試圖找出哪些行不存在於兩個惡化的日期之間。按條件在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 
+3

什麼是邏輯? – Kaf

+2

我不明白你在做什麼。您返回的行在上面的數據庫中。如果你看ID 456和789,唯一的區別就是ID。您是否想要爲每個日期返回ID最高的行? –

+0

如果在那些年份還有其他年份或其他日期,該怎麼辦? – Aioros

回答

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 
        ) 
       ) 
+0

謝謝Gordon ......但是這對我的'更清晰'的例子不起作用 – jedd

+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