I have some sample data, for example:
INSERT INTO mytable ([ID], [FK_ID], [TYPE_ID]) VALUES (1, 10, 1), (2, 11, 1), (3, 11, 2), (4, 12, 1), (5, 12, 2), (6, 12, 3), (7, 14, 2), (8, 14, 3)
Now I'm trying to check if each group FK_ID exact match of the values TYPE_ID 1 & 2 .
So, the expected result is as follows:
(1, 10, 1) this will not work- As in the group
FK_ID = 10 , we have only one record
(2, 11, 1), (3, 11, 2) this should go- As in the group
FK_ID = 11 , we have two entries. - And both
TYPE_ID correspond to the values 1 & 2 .
(4, 12, 1), (5, 12, 2), (6, 12, 3) this should also fail(7, 14, 2), (8, 14, 3) this should also fail- Despite the fact that we have two entries, it does not work, since the
TYPE_ID does not match the values 1 & 2 .
Here is my attempt:
select * from mytable t1 where exists (select count(t2.TYPE_ID) from mytable t2 where t2.FK_ID = t1.FK_ID and t2.TYPE_ID in (1, 2) group by t2.FK_ID having count(t2.TYPE_ID) = 2);
This does not work as expected, because it also passes for FK_ID = 12 , which has three entries.
Demo: SQL Fiddle
sql sql-server sql-server-2008
CodeNewbie
source share