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

Selecione para calcular a média de vendas por cliente levando as primeiras vendas na conta MYSQL


Isso deve ajudá-lo
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