2016-08-04 104 views
0

我的表看起來像/減少一組數據:百分比增加一個MySQL表

|| date || bytes || table || 

我需要制定出基於規模和年中的所有表的年增長率(增減百分比) 。我有一個查詢,主要是給我我想要的信息,我可以解析並使用外部工具來生成所需的數據,但我想知道是否有一種簡單的方法直接在查詢中執行百分比增加計算?

這是我的查詢的外觀現在:

SELECT 
    YEAR(date) AS YEAR, 
    table, 
    SUM(bytes)/1024/1024/1024 AS total 
FROM 
    insertions 
GROUP BY table, YEAR (date) 
ORDER BY date; 

是否有可能有一個具有電流相對於前一年的表的百分比增加/減少一個領域?

輸出示例:

| date | bytes | table  | 
| 2015 | 100 | accounting | 
| 2016 | 150 | accounting | 
| 2015 | 1  | it   | 
| 2016 | 100 | it   | 

隨着增加的百分比,它應改爲如下所示:

| date | bytes | table  | percentage 
| 2015 | 100 | accounting | 0 
| 2016 | 150 | accounting | 50 
| 2015 | 1  | it   | 0 
| 2016 | 100 | it   | 9900 
+0

您能否顯示一些示例數據和預期結果 – TheGameiswar

+0

MySQL是否執行該查詢?!? – jarlh

+0

是的,它確實正確執行和生成每個表/每年的分組。 – CaseyJones

回答

1

這樣做使用變量來獲取前值的一種方法:

SELECT year, table, total, 
     (@prev := (case when (@new_prev := @prev) = null 
         then 'never go here' 
         when @t = table 
         then if(@prev := total, @new_prev, @new_prev) 
         when @t := table 
         then if(@prev := total, NULL, NULL) 
        end) 
     ) as prev_total 
    FROM (SELECT YEAR(date) AS YEAR, table, SUM(bytes)/1024/1024/1024 AS total 
     FROM insertions i 
     GROUP BY table, YEAR (date) 
     ) yt CROSS JOIN 
     (SELECT @t := '', @prev := -1) params 
    ORDER BY table, date 

其餘的只是算術使用子查詢來獲得差異。

注意:這是特別具有挑戰性的,因爲所有使用變量的公式必須在單個表達式中。 MySQL不保證SELECT中表達式的求值順序,所以不能安全地在多個表達式(帶賦值)中使用變量。