0

How can I query a Microsoft SQL table to return only the InstNum that has all Profile types C or U?

Please see my table structure below.

InstNum Profile
001 U
001 C
001 U
002 U
002 U
002 U
003 C
003 C
003 C

I tried :

Select InstNum from Table Where Profile = 'C' Group By InstName;

But I received the results:

InstNum
001
002
003

I was expecting to receive:

InstNum
003

Because the InstNum of 0003 is the only one where all the Profiles are C.

What am I doing wrong? Does anybody have an idea how I can achieve this?

1
  • Why not 002 ? Isn't your condition return only an InstNum that has all Profile type 'C' or 'U' ?
    – Squirrel
    May 12, 2022 at 2:12

2 Answers 2

1

Try using an EXCEPT…

SELECT InstNum
FROM Table
WHERE Profile = 'C'

EXCEPT

SELECT InstNum
FROM Table
WHERE Profile <> ‘C'
GROUP BY InstNum;
0
0
WITH sameProfiles AS
  (
    SELECT
      COUNT([instNum]) cnt
      , [instNum]
    FROM
      (
        SELECT distinct
          [instNum]
          , [Profile]
        FROM
          myTable1 ) q
    GROUP BY
      [instNum]
    HAVING
      COUNT([instNum]) = 1)
SELECT DISTINCT
  [instnum]
FROM
  myTable1
WHERE
  [profile] = 'C'
and [instNum] in
  (
    SELECT
      [instNum]
    FROM
      sameProfiles);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.