Вопрос

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?

Это было полезно?

Решение

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)

Другие советы

select cust_ID 
from table 
group by cust_ID  
having max(status) = 'd' 
and min(status) = 'd' 

This is called Relational Division and @Andy and @Paparazzi has given two solutions for it. Yet another variant is:

SELECT Cust_ID
FROM Tbl t 
GROUP BY Cust_ID
HAVING COUNT(DISTINCT Status) 
     = COUNT(DISTINCT CASE WHEN STATUS = 'D' THEN Status END)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с dba.stackexchange
scroll top