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

A consulta para obter o total de pedidos feitos por algum cliente específico no ano passado recupera datas repetidas quando não existe nenhum pedido


Para contar o total de pedidos feitos mensalmente no ano passado por um cliente específico, use esta consulta:
SELECT MONTHNAME(c.datefield) AS Month, 
    YEAR(CURRENT_DATE - INTERVAL 1 YEAR) AS Year, 
    IFNULL(o.TotalOrders, 0) AS Orders 
    FROM calendar AS c 
    LEFT JOIN (
        SELECT MONTH(o.order_date) AS Month, 
        YEAR(o.order_date) AS Year, 
        COUNT(o.customer_id) AS TotalOrders 
        FROM orders AS o 
        WHERE YEAR(o.order_date) = YEAR(CURRENT_DATE - INTERVAL 1 YEAR) AND o.customer_id = 329 
        GROUP BY Month) AS o 
    ON MONTH(c.datefield) = o.Month 
    GROUP BY MONTH(c.datefield)