2016-01-27 59 views

回答

1

嘗試避免內部聯接,它有錯誤的情況呢(t1.hitDate = t2.hitDate and t1.hitDate-1 = t2.hitDate不能滿足):

select 
    t1.HitDate, 
    t1.City, 
    t1.Client, 
    SUM(t1.NumVisits) - IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0) as rate_of_change 
from 
    PAGE_HITS t1 
WHERE 
t1.Client='C' 
group by 
    HitDate, 
    City 
    ORDER BY HitDate; 
+0

你好Zbynek - 非常感謝。我已經更新了小提琴以包含更多值來測試。 http://www.sqlfiddle.com/#!9/29c94c/1 - 看起來它只顯示原始數據值而不是變化率。另外,我希望以百分比形式顯示更改率。 – usert4jju7

+0

這對每一行都是有意義的,以前的日期沒有行。插入一些數據以獲得差異。關於百分比 - 將'-'更改爲'/'。 –

+0

謝謝Zbynek。非常感謝您的幫助。我已經在下面發佈了我的答案,只是爲了獲得基於百分比的計算的完整參考。 – usert4jju7

0

要獲得基於百分比增加/減少

select 
    t1.HitDate, 
    t1.City, 
    t1.Client, 
    SUM(t1.NumVisits), 
    IFNULL(((SUM(t1.NumVisits) - IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0)) * 100)/IFNULL((SELECT SUM(t2.NumVisits) FROM PAGE_HITS t2 WHERE t2.HitDate = t1.HitDate-1 AND t2.City = t1.City AND t2.Client = t1.Client), 0),0) as rate_of_change 
from 
    PAGE_HITS t1 
WHERE 
t1.Client='C' 
group by 
    HitDate, 
    City 
    ORDER BY HitDate; 
0

先做一個唯一編號像rownum 並作出相同的查詢 和加入rownum列 然後你可以看到前一個月作爲新列和計算變化率。

SELECT A.HitDate, A.City, A.sumThis, B.sumFormer, (A.sumThis/B.sumFormer - 1) * 100 as 'ChangingRate' 
From (
     select @rownum1:[email protected] + 1 as 'rownum1', HitDate, City, sum(NumVisits) as 'sumThis' 
     from page_hits, (Select @rownum1:=0) R 
     Where client = 'C' 
     Group by HitDate, City 
     ) A 
Left Join (
     select @rownum2:[email protected] + 1 as 'rownum2', HitDate, City, sum(NumVisits) as 'sumFormer' 
     from page_hits, (Select @rownum2:=0) R 
     Where client = 'C' 
     Group by HitDate, City 
     ) B On A.rownum1 - 1 = B.rownum2