Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Agregação de tabela cruzada / pivô do MySQL. Removendo contagens com base na coluna em outra tabela

SELECT
    CASE
        WHEN ci.make_model LIKE "Acura%" THEN "Acura"
        WHEN ci.make_model LIKE "Ford%" THEN "Ford"
        WHEN ci.make_model LIKE "Toyota%" THEN "Toyota"
        WHEN ci.make_model LIKE "Tesla%" THEN "Tesla"
    END AS Make,
    SUM(CASE WHEN ci.color = "Black" THEN 1 ELSE 0 END) as Black,
    SUM(CASE WHEN ci.color = "Blue" THEN 1 ELSE 0 END) as Blue,
    SUM(CASE WHEN ci.color = "White" THEN 1 ELSE 0 END) as White
FROM car_inventory ci
WHERE 
    (ci.year > 2012) and
    (ci.car_id not in (select distinct il.car_id from inventory_log il where il.note like '%issue%'))
GROUP BY Make
ORDER BY Make;