我有一个简单的计数器表:
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小时pr类型做一个图表,并跳过那些带有0的图表。这样我得到的图表是x轴上的每小时和y轴上的访问。然后是四个累积图,每种类型一个,总共一个。
到目前为止,我得到了以下声明,它只给了我没有类型的pr小时。我需要一些帮助才能将其演变为上述内容。
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
我认为这将为我提供执行所需图表的数据
答案 0 :(得分: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
放在外部查询中。