比较本周至去年同一周的财务数据

时间:2014-04-10 11:21:59

标签: mysql sql

我需要比较本周到去年同一周的财务数据..我的表是

        amount  storecode   date
        0.00    0000000001  2010-12-21 14:01:00
        0.00    0000000001  2010-12-21 14:01:00
        0.00    0000000001  2010-12-21 14:57:50
        10.00   0000000001  2010-12-21 14:57:50
        2.35    0000000001  2010-12-21 14:57:50
        45.00   0000000001  2010-12-21 14:57:50
        0.00    0000000001  2010-12-21 14:57:50
        -10.00  0000000001  2010-12-21 14:57:50
        -2.35   0000000001  2010-12-21 14:57:50
        -45.00  0000000001  2010-12-21 14:57:50
        ...................etc...etc to 2014

我尝试了很多不同的时间间隔,但我找不到一些对我的老板来说准确无误的事情,看看本周和去年同一周之间的比较..

我甚至尝试将其与另一个表连接,以便为商店代码提供无法识别的视觉表示而非数字形式

        SELECT distinct(`stores`.`StoreLocation`) as branch, SUM(`TRANSACTIONS`.`Amount`) as AmountTendered , DATE(`TRANSACTIONS`.`Date`) as Dates FROM transactions LEFT JOIN stores ON stores.StoreCode = transactions.Storecode WHERE DATE_SUB(CURDATE(),INTERVAL 1 year) <= DATE(Date) group by YEAR(Date) 

1 个答案:

答案 0 :(得分:0)

你不能确信自己理解自己的想法(或者更具体地说,你的老板想要将一周的价值与一年之间的关联联系起来(主要是以月为单位并且它可以在一周或2周内出现

以下是基于您分享的数据的起点

去年报告的例子

SELECT YEAR(`date`) AS `year`
    , WEEKOFYEAR(`date`) AS weekno
    ,Storecode AS storecode
    , SUM(amount) AS amount
FROM transactions
WHERE YEAR(`date`) = YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR))
GROUP BY YEAR(`date`), WEEKOFYEAR(`date`), Storecode

以下是带有比较的查询示例

SELECT this.storecode 
   , this.weekno
   , this.amount AS current_amount
   , history.amount AS past_amount
FROM (SELECT YEAR(`date`) AS `year`
        , WEEKOFYEAR(`date`) AS weekno
        ,Storecode AS storecode
        , SUM(amount) AS amount
      FROM transactions
      WHERE YEAR(`date`) = YEAR(NOW())
      GROUP BY YEAR(`date`), WEEKOFYEAR(`date`), Storecode) AS this
JOIN (SELECT YEAR(`date`) AS `year`
        , WEEKOFYEAR(`date`) AS weekno
        ,Storecode AS storecode
        , SUM(amount) AS amount
      FROM transactions
      WHERE YEAR(`date`) = YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR))
      GROUP BY YEAR(`date`), WEEKOFYEAR(`date`), Storecode) AS history
  ON this.weekno = history.weekno
    AND this.storecode = history.storecode;