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

Seleccione para calcular el promedio de ventas por cliente teniendo en cuenta las primeras ventas MYSQL

Esto debería ayudarte

SELECT Customer, (total_sales/weeks) AS avg_sales FROM
(
SELECT Customer, total_sales, Date_First_Sale, IF(weeks>52,52,weeks) as weeks
FROM (
    SELECT Customer, SUM(Sales) AS total_sales, Date_First_Sale, TIMESTAMPDIFF(WEEK, Date_First_Sale, CURDATE()) AS weeks
    FROM (
        SELECT Customer, sales , Date_First_Sale
        FROM test.SO_customer
        WHERE Date > DATE_SUB(curdate(), INTERVAL 1 YEAR)
         ) as subTable
    GROUP BY Customer
    ) as subTable2
) as subTable3