Sql-server – Distinct in one column where another column has same values

distinctsql server

I have a table sample

  id   |  name  | type
-------+--------+------
 PR001 | DC001  |    a
 PR002 | DC001  |    a
 PR003 | DC001  |    b
 PR004 | DC002  |    a
 PR005 | DC003  |    a
 PR006 | DC003  |    a
 PR007 | DC004  |    b
 PR008 | DC005  |    c

Is there a way to display distinct for column name only if where column type should be all the same value ('a')

output I want to achieve

 name   | type
---------+------
 DC002  |    a
 DC003  |    a

Any help would be greatly appreciated

Best Answer

SELECT name, MIN(type) AS type 
FROM table_name 
GROUP BY name
HAVING COUNT(DISTINCT type) = 1 ;

or the same with:

HAVING MIN(type) = MAX(type)

I assume that type is not nullable.

If you want only those that have type = 'a', use:

HAVING MIN(type) = 'a'
   AND MAX(type) = 'a' ;