Click here to Skip to main content
14,880,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My data looks something like this:
Key        ColA          ColB
0001          007           X012           **

0002          007           X012
0002          008           X012
0002          011           X012

0003          007           X012           **

0004          007           X012
0004          008           X012

What I am trying to do is return only those keys that have column A = '007' and Column 'B' = 'X012' BUT no other rows for the same key can have an 'X012' value.
Looking at the data above I want only the rows marked with ** returned as they contain 007 and X012 but no other rows that contain X012.

What I have tried:

I have tried using NOT IN , I have tried EXCEPT , using EXISTS with NOT EXISTS, SELECT within SELECT but I either get all data returned that includes X012 or I get no data returned.
Updated 7-Feb-20 2:41am

Use GROUP BY to limit the Key values, and then JOIN that with your original table:
SELECT a.[Key], a.ColA, a.ColB 
FROM MyTable a
      GROUP BY [Key] 
      HAVING COUNT([Key]) = 1) b
  ON a.[Key] = b.[Key]
WHERE a.ColA = '007'
  AND a.ColB = 'X012'
Maciej Los 7-Feb-20 8:43am
Interesting... You are getting data if group count is equal to 1, but i'm getting data where key column has odd value...

OriginalGriff 7-Feb-20 8:45am
I suspect he may want to add "AND ColB = 'X012'" to the HAVING clause, but from his example it's difficult to tell.
OriginalGriff 7-Feb-20 8:47am
Or similar - that wouldn't compile as ColB is not in the GROUP BY clause - it'd be a new WHERE clause, obviously :doh:
If you want to get data for odd values in key column:
FROM TableName
WHERE ColumnA = '007' AND ColumnB = 'X012' AND CONVERT(ColumnKey, INT) % 2 != 0

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900