2017-04-25 34 views
0

累積總和我有一個簡單的計數器表:獲取每小時

date     action  type 
2017-04-25 11:41:38 +1   type_1 
2017-04-25 11:66:22 +1   type_2 
2017-04-25 12:41:32 -1   type_1 
2017-04-25 12:55:38 +1   type_3 
2017-04-25 13:02:11 -1   type_1 

我希望做一個圖形,累計參觀PR公關每小時類型和跳過那些0。所以,我得到一個圖表,每隔一小時在X軸上和在Y軸上訪問。然後是四個累積圖表,每個類型和一個總數。

到目前爲止,我得到了以下聲明,只是給出了沒有類型的總和小時數。我需要一些幫助來將其發展到上面描述的狀態。

SELECT DATE_FORMAT(date, '%W %k:00') as weekday, DATE_FORMAT(date, '%d-%m-%Y %k:00') as full_date, SUM(action) as total 
FROM  counter 
GROUP BY HOUR(date) 

期望的結果:

date     total   type 
2017-04-25 11:00  3    type_1 
2017-04-25 11:00  5    type_2 
2017-04-25 11:00  8    type_3 
2017-04-25 11:00  16   total 
2017-04-25 12:00  6    type_1 
2017-04-25 12:00  9    type_2 
2017-04-25 12:00  14   type_3 
2017-04-25 12:00  29   total 

我認爲這會爲我提供的數據做所需的圖形

+2

用你正在使用的數據庫標記你的問題。在問題中提供預期的結果。 –

回答

0

首先,按小時彙總數據:

select date_format(date, '%Y-%m-%d %H') as yyyymmddhh, type, sum(action) as cnt 
from counter 
group by yyyymmddhh, type; 

接下來,您可以使用變量獲取累計值:

select yyyymmddhh, type, cnt, 
     (@cs := if(@t = type, @cs + cnt, 
        if(@t := type, cnt, cnt) 
       ) 
     ) as cumulative_cnt 
from (select date_format(date, '%Y-%m-%d %H') as yyyymmddhh, type, sum(action) as cnt 
     from counter 
     group by yyyymmddhh, type 
    ) c cross join 
    (select @t := '', @cs := 0) params 
order by type, yyyymmddhh; 

如果需要按不同順序輸出結果,則將其用作子查詢,並將order by置於外部查詢中。