Mysql
 sql >> Database >  >> RDS >> Mysql

La query per ottenere il totale degli ordini effettuati da un cliente specifico nell'ultimo anno recupera le date ripetute quando non esiste alcun ordine

Per contare gli ordini totali effettuati mensilmente nell'ultimo anno da un determinato cliente, utilizza questa query:

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)