Select one column with same value and check another column's value
-
03-10-2020 - |
Вопрос
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_ID
s have multiple Status
in different rows.
Now I want to pick Cust_ID
s 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)
Не связан с dba.stackexchange