2014-04-10 105 views
0

我需要從本週比較財務數據爲去年同一週..我的表是從本週比較財務數據爲去年同一週

 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

大概的第一件事是查詢的例子澄清是如何定義前一年的同一周?從同一日期?相同的ISO週數?從星期一到星期日?從本月的第n個星期一開始? – Glenn

+0

它只是主要按月走,因爲我們的業務是季節性的,所以它很好地看到這些數字,它可以超過一週或2 – Kravitz

+0

您是否被允許創建一個臨時表?粗略地說,我要做的是創建另一個表格,其中原始數據按WeekOfYear(日期)和Year(日期)分組並彙總;然後在新表上進行自連接以進行比較。 –

回答

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; 
+0

非常好,但是當我試圖添加StoreCode這本質上是一個ID,它不給我正確的結果,但確實很不錯。有5個不同的商店代碼,我如何得到比較,並進一步細分他們 – Kravitz

+0

你必須在所有這些地方添加商店代碼。 (1)主'SELECT'; (2)括號內的兩個「SELECT」子句中的每一個; (3)括號中的兩個「GROUP BY」條款中的每一個; (4)最後的「ON」子句(對此使用「AND」)。 –

+0

......正如最新的編輯所展示的那樣。 –