MySQL - 本周与去年同一周相比较

时间:2012-08-10 01:48:22

标签: mysql sql

如何获得本周与去年同一周的销售总额之和?

有两种可能的情况与日期的存储方式有关,如下所示:

情景1

**Sales**

Date          Sales    
-----------------------   
2012-08-10    11040.00
2012-08-09    11500.00
2012-08-08    14060.00
2012-08-07    93000.00
2012-08-06    11200.00
...
2011-08-10    11040.00
2011-08-09    11500.00
2011-08-08    14060.00
2011-08-07    93000.00
2011-08-06    11200.00

场景2

**Sales**

year         month       day         Sales
---------------------------------------------       
2012         08          10          11040.00
2012         08          09          11500.00
2012         08          08          14060.00
2012         08          07          23000.00
2012         08          06          11200.00
...
2011         08          10          13040.00
2011         08          09          11500.00
2011         08          08          12060.00
2011         08          07          33000.00
2011         08          06          11250.00

1 个答案:

答案 0 :(得分:3)

对于您的第一个方案,请加入WEEKOFYEAR()上的同一个表格,并添加到去年的YEAR()

SELECT
  YEARWEEK(thisyear.Date) AS `YearWeek`
  SUM(lastyear.Sales) AS LastYearSales
  SUM(thisyear.Sales) AS ThisYearSales
FROM
  Sales thisyear
  LEFT JOIN Sales lastyear ON
      WEEKOFYEAR(thisyear.Date) = WEEKOFYEAR(lastyear.Date) 
      AND YEAR(thisyear.Date) = (YEAR(lastyear.Date) + 1)
GROUP BY `YearWeek`

第二种情况需要从3个单独的值中构建日期。我认为这将起作用:

SELECT
  YEARWEEK(CONCAT_WS('-', thisyear.year, thisyear.month, thisyear.day)) AS `YearWeek`,
  SUM(lastyear.Sales) AS LastYearSales,
  SUM(thisyear.Sales) AS ThisYearSales
FROM
  Sales thisyear
  LEFT JOIN Sales lastyear ON
    WEEKOFYEAR(CONCAT_WS('-', thisyear.year, thisyear.month, thisyear.day)) = WEEKOFYEAR(CONCAT_WS('-', lastyear.year + 1, lastyear.month, lastyear.day))
GROUP BY `YearWeek`