2014-05-04 90 views
0

我有一個名爲table1表中的SQL Server 2008過濾器的SQL Server記錄

它具有以下數據:

id refId Date   IsActive 
===================================== 
1  2  2014-03-01   1 
2  2  2014-03-01   1 
3  2  2014-04-15   0 < 
4  2  2014-04-15   0 < 
5  2  2014-05-20   1 
6  2  2014-05-20   1 
7  4  2014-03-01   1 
8  4  2014-03-01   1 
9  4  2014-04-15   1 < 
10 4  2014-05-20   1 

編輯

refId是指一個人在另一個表。所以,我想其記錄的人沒有Date = 2014-04-15或者他們有Date = 2014-04-15IsActive = 0

所以根據上面,輸出應該是:

refId 
===== 
2 

我可以使用此查詢通過MySQL做到這一點( EDIT 2):

SELECT refId 
FROM table1 
GROUP BY refId 
/*Check if there is no value with this date*/ 
HAVING MAX(Date='2014-04-15') = 0 
/*Check if the date exists but the IsActive flag is off*/ 
OR MAX(Date='2014-04-15' AND IsActive=0) = 1 

但問題是,SQL Server不接受該MAX()功能狀態。

+0

你可以輸入樣本輸出嗎? –

回答

1

,如果你只需要包括滿足您要求的refIds,那麼這應該工作

select refId 
from table1 as t 
group by refId 
having exists(
    select refId 
    from table1 as t2 
    where [Date]<>'2014-04-15' 
    or ([Date]='2014-04-15' and IsActive=0) 
    group by refId 
    having t.refId=t2.refId 
-- this next line is where we make sure we are only matching 
-- where the total number of records of refId is equal to the total match count 
    and count(t.refId)=count(t2.refId) ) 
+0

謝謝,這解決了這個問題。 – Ayman

0
SELECT DISTINCT refId 
FROM table1 


WHERE (Date!='2014-04-15') 

OR (Date='2014-04-15' AND IsActive=0) 

輸出:

 refId 
     ===== 
     2 
1

如果這是在MySQL查詢:

SELECT refId 
FROM table1 
GROUP BY refId 
HAVING MAX(Date='2014-04-15') = 0 OR 
     MAX(Date='2014-04-15' AND IsActive=0) = 1; 

你可以重新adily使用case語句翻譯這個到SQL Server/ANSI SQL語法:

SELECT refId 
FROM table1 
GROUP BY refId 
HAVING MAX(CASE WHEN Date = '2014-04-15' THEN 1 ELSE 0 END) = 0 OR 
     MAX(CASE WHEN Date = '2014-04-15' AND IsActive = 0 THEN 1 ELSE 0 END) = 1; 

該查詢也將在MySQL工作。

+0

謝謝,這也解決了這個問題。 – Ayman