2016-01-08 86 views
1

我有了記錄,像這樣的表:SQL Server和自我選擇加入

FieldId collationid Type Message 
--------------------------------------------- 
1   1234   WC  hello 
2   1234   WR  next message 
3   1234   WZ  again 
4   1234   WX  another message 
5   ab12   WC  this message 
6   ab12   WR  again 
7   ab12   WZ  misc message 
8   5678   WC  hello 
9   5678   WR  next message 
10  5678   WZ  again 
11  5678   WX  another message 

一個記錄是完整的,當它擁有所有四個記載,WC,WR,WZ和WX。我需要一個sql來顯示我什麼時候缺少一條記錄。在前面的表格示例中,SQL將生成ab12,因爲它只有WC,WR和WZ記錄。

感謝任何幫助,您可以給我..

回答

3

使用COUNT()HAVING

SELECT collationid 
FROM tbl 
WHERE Type IN('WC', 'WR', 'WZ', 'WX') 
GROUP BY collationid 
HAVING COUNT(DISTINCT Type) < 4 
+0

你必須非常快的手指;-)這將是我建議的回答也是如此。 Upvoting ... – Cahit