sql >> Base de Datos >  >> RDS >> Mysql

SQL:obtenga registros que satisfagan las condiciones provenientes de múltiples registros

Por pregunta:get a list of customers who bought both A and B

SELECT  CustomerID
FROM    CustomerList
WHERE   ProductID IN ('A', 'B')
GROUP   BY CustomerID
HAVING  COUNT(*) = 2

si la unicidad no se hizo cumplir en ProductID para cada CustomerID , DISTINCT se requiere palabra clave,

SELECT  CustomerID
FROM    CustomerList
WHERE   ProductID IN ('A', 'B')
GROUP   BY CustomerID
HAVING  COUNT(DISTINCT ProductID ) = 2

Para la segunda pregunta, "..A y C y D pero no B y E y F"

SELECT  CustomerID
FROM    CustomerList
WHERE   ProductID IN ('A', 'C', 'D')
GROUP   BY CustomerID
HAVING  COUNT(*) = 3 AND
        CustomerID NOT IN
        (
            SELECT  CustomerID
            FROM    CustomerList
            WHERE   ProductID IN ('B','E','F')
        )