Sql-server – Query Relating Rows W/O A Corresponding Value

sql servert-sql

I have a table setup like this:

ID Code      DateActive   DateInactive  statusCode
  15          20090413       null           A
  15            null         20090416       I
  15          20100101       20130101       I
  16          20130515       20151225       I
  16          20151226       20160101       I

I want to pull results that do not possess a status code of "A" in any of the corresponding rows. For example, in the table above, I would want only the result set from 16, with a single result grouping all of the possible rows.

    Desired Result:
ID Code       StatusCode
  16               I

I only want those that have an I and do not have an A row in my results.

Have a feeling this might be an easy one, but I can't seem to find a way to solve it.

Best Answer

SELECT [ID Code], statusCode
  FROM dbo.Table AS t
  WHERE NOT EXISTS 
  (
    SELECT 1 FROM dbo.Table 
    WHERE [ID Code] = t.[ID Code]
    AND statusCode = 'A'
  )
  GROUP BY [ID Code], statusCode;