2017-02-05 110 views
0


我需要一些幫助來創建mysql語句。我有銷售表記錄每日sals數據。 現在,我想比較過去3年並列的每週銷售數量。Mysql查詢並排比較過去3年的每週數據

以下是sqlfiddle中的示例數據。

這是我到目前爲止已經試過,但只返回一個星期的數據:

SELECT YEARWEEK(s1.sale_date,1) AS weekY1, SUM(s1.total) AS totalY1, 
        YEARWEEK(s2.sale_date,1) AS weekY2, SUM(s2.total) AS totalY2, 
        YEARWEEK(s3.sale_date,1) AS weekY3, SUM(s3.total) AS totalY3 
      from sales_chc s1 
      LEFT JOIN sales_chc s2 
      ON s2.sale_date = (s1.sale_date -INTERVAL 1 YEAR) 
      LEFT JOIN sales_chc s3 
      ON s3.sale_date = (s1.sale_date -INTERVAL 2 YEAR) 
      WHERE YEAR(s1.sale_date) = '2017' AND YEARWEEK(s1.sale_date, 1) = YEARWEEK(CURDATE(), 1)-1 
      GROUP BY YEARWEEK(s1.sale_date, 1) 
+1

什麼是你期望的結果根據您的樣本數據? – Blank

+0

我希望每個星期(至日期)都列出其每年的總銷售額。 – sohal07

+0

您的GROUP BY看起來有點可疑,而不是您的WHERE子句將它限制爲與當前YEARWEEK(減1,而我不確定有效)相等**的YEARWEEK? –

回答

0

試試這個:

SELECT WEEKOFYEAR(s1.sale_date) as WEEKNUM, 
SUM(case when YEAR(s1.sale_date) = '2017' then s1.total else 0 end) AS total2017, 
SUM(case when YEAR(s1.sale_date) = '2016' then s1.total else 0 end) AS total2016, 
SUM(case when YEAR(s1.sale_date) = '2015' then s1.total else 0 end) AS total2015 
from sales_chc s1 
GROUP BY WEEKOFYEAR(s1.sale_date)