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

Selezionare per calcolare la media delle vendite per cliente che prende le prime vendite nell'account MySQL

Questo dovrebbe aiutarti

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