我在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 |
+-----------+------------+-------+-----------------+
我需要计算过去12个月内每周计算的平均销售额(52或53周,具体取决于日历?),从今天开始计算。
现在的问题是,我不想计算客户在12个月以下的首次购买时的平均每周销售额,例如当前日期是2016-09-01,而客户是他在2016-07-24的首次购买,平均值不应按12个月计算,而应仅按2016-07-24与2016-09-01之间的每周销售额计算。
对于在12个月之前进行首次购买的客户,平均值应仅在12个月内计算。
我一直试图找到这个SELECT,但由于我对更复杂的查询有限的Mysql知识而没有达到任何目的!
提前感谢您的帮助
答案 0 :(得分:0)
这应该可以帮到你
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