Renaud DUGERT Renaud DUGERT - 2 months ago 7
MySQL Question

Select to Calculate Sales Average by Customer taking First Sales into Account MYSQL

I have this Sales Table by Customer in Mysql

+-----------+------------+-------+-----------------+
| Customer | Date | Sales | Date_First_Sale |
+-----------+------------+-------+-----------------+
| Jane | 2016-04-30 | 903 | 2015-02-03 |
| Jane | 2016-02-03 | 51 | 2015-02-03 |
| Jane | 2016-03-09 | 192 | 2015-02-03 |
| John | 2016-05-10 | 64 | 2015-10-03 |
| John | 2016-04-16 | 880 | 2015-10-03 |
| John | 2016-08-17 | 386 | 2015-10-03 |
| John | 2016-03-01 | 503 | 2015-10-03 |
| Juan | 2016-07-06 | 765 | 2015-09-01 |
| Juan | 2016-01-20 | 36 | 2015-09-01 |
| Juan | 2016-03-03 | 928 | 2015-09-01 |
| Momo | 2016-06-29 | 573 | 2015-09-01 |
| Momo | 2016-04-25 | 375 | 2015-09-01 |
| Momo | 2016-06-10 | 999 | 2015-09-01 |
| Nour | 2016-02-28 | 956 | 2015-05-01 |
| Nour | 2016-01-03 | 582 | 2015-05-01 |
| Nour | 2016-08-17 | 366 | 2015-05-01 |
| Philip | 2016-03-22 | 296 | 2015-09-01 |
| Philip | 2016-04-14 | 459 | 2015-09-01 |
| Sylvie | 2016-03-29 | 551 | 2015-09-03 |
| Sylvie | 2016-02-14 | 896 | 2015-09-03 |
+-----------+------------+-------+-----------------+


I need to calculate the Average Sales by Customer calculated on a WEEKLY basis in the last 12 months (52 or 53 weeks depending on the calendar?), starting from Today.

Now the problem is that I do not want to calculate the Average Weekly sales by customer for customers that have made their first purchase in a range below 12 months, for instance If current date is 2016-09-01, and Customers made his first purchase on 2016-07-24, the average should not be calculated on a 12 months basis but on the weekly sales generated between the 2016-07-24 and the 2016-09-01 only.

For customers who have made their First purchase before the 12 months range, then the average should be calculated on 12 months only.

I have been trying to find this SELECT but have not reached anything due to my limited Mysql knowledge for more complex queries!

Thanks in advance for your help

Answer

This should help you

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
Comments