Query – How to Select One Column with Same Value and Check Another Column’s Value

queryrelational-division

I have a table with following structure (rest of the columns omitted for brevity) :

+------------+-------+
 | Cust_ID    | Status|
 +------------+-------+
 | 312        | A     |
 | 312        | D     |
 | 312        | D     |
 | 345        | A     |
 | 345        | D     |
 | 345        | A     |
 | 678        | D     |
 | 678        | D     |
 | 678        | D     |
 +------------+-------+

We can observe that same Cust_IDs have multiple Status in different rows.
Now I want to pick Cust_IDs for which all Status row is D. So in the above case, the Cust_ID 678 should be listed.

Can anybody help me out in writing such query?

Best Answer

I only use T-SQL, but I don't think anything used below is specific to SSMS:

SELECT DISTINCT Cust_ID
FROM Tbl t
WHERE
    Status = 'D'
AND NOT EXISTS (SELECT * FROM Tbl WHERE Status <> 'D' AND Cust_ID = t.Cust_ID)