2

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

与如何存储日期有关的可能方案有两种,如下所示:

方案 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
4

1 回答 1

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`
于 2012-08-10T03:04:23.323 回答