2

昨年の同じ週に対する現在の週の売上合計を取得するにはどうすればよいですか?

以下のように、日付の保存方法に関連する 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`

2 番目のシナリオでは、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 に答える