I need help from a SQL guru here…
I have data in the following format:
Key Value
100 A
100 B
300 A
400 B
500 A
500 B
500 C
600 B
600 W
If I want to find all keys with A or B and A and B, but not AB with anything else…how would I do this? Would I need a temp table or can I somehow join the table to itself?
EDIT: The desired output would be Key 100 since it has A & B, Key 300 since it has A, Key 400 since it has B. Not Key 500 because it also contains a C, and not key 600 because it also contains a W
This should work for you:
SQL Fiddle Demo
This returns only the keys:
AandBonly, and nothing else sokey = 500shouldn’t be returned. Butkey = 100should be included.A. As inkey = 300.Bsokey = 600shouldn’t be returned since it contains one more value thanBwhich isw. Butkey = 400should be included.Update: How is this working
If any key has a value
IN('A', 'B')then it could also contains other values as well.Thats why I added the
HAVINGclause:The
COUNT(t1.value)is compared to the totalCOUNTof the values for the same key, by using a correlated subquerySELECT COUNT(t2.value) FROM Table1 t2 WHERE t1.key = t2.key, for each valuet1.value. So if the current key contains values other than'A', 'B'then theCOUNT(t1.value)won’t equal to theCOUNTof all values for the same key. For example the key = 500 has a count = 3 but using:Without the
HAVINGclause will include it as well, since it has eitherA'or ‘B’. But theHAVINGclause eliminates this key since it has a count = 3 not equal to 2.