我想检索一个图表的数据,我想为它提出一个简单的解决方案,而不是做8个子查询.
这就是users表格的样子:
user_id
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)
这就是pts表格的样子:
id user_id status points time
1 1 0 100 2014-08-23 03:34:54
2 4 0 100 2014-08-23 04:04:44
3 1 1 300 2014-08-23 08:34:21
4 1 0 300 2014-08-23 15:25:11
5 1 0 200 2014-08-23 22:23:12
Run Code Online (Sandbox Code Playgroud)
查询看起来像这样(带有一些注释,我不知道要放什么):
"SELECT *,
(
SELECT SUM(points)
FROM pts
WHERE status = 0
AND user_id = 1
AND time >= "THIS DAY'S 00:00" AND <= "THIS DAY'S 03:00"
),
(
SELECT SUM(points)
FROM pts
WHERE status = 0
AND user_id = 1
AND time >= "THIS DAY'S 03:00" AND <= "THIS DAY'S 06:00"
),
(
SELECT SUM(points)
FROM pts
WHERE status = 0
AND user_id = 1
AND time >= "THIS DAY'S 06:00" AND <= "THIS DAY'S 09:00"
),
(
SELECT SUM(points)
FROM pts
WHERE status = 0
AND user_id = 1
AND time >= "THIS DAY'S 12:00" AND <= "THIS DAY'S 15:00"
),
"ETC......"
FROM pts
WHERE user_id = 1
AND status = 1
"
Run Code Online (Sandbox Code Playgroud)
因此,基本上查询需要在当天每隔3小时从数据库收集数据(因此,如果我选择上述选项,那么将是8个子查询).如果该时间间隔尚未达到当前时间,则查询应返回0/null.如果当前时间处于其中一个间隔中,则它应该从间隔的开始直到间隔的结束返回数据.
我希望实现的结果:
id user_id points time
1 1 0 2014-08-23 00:00:00 - 2014-08-23 03:00:00
2 1 200 2014-08-23 03:00:00 - 2014-08-23 06:00:00
3 1 300 2014-08-23 06:00:00 - 2014-08-23 09:00:00
4 1 0 2014-08-23 09:00:00 - 2014-08-23 12:00:00
5 1 0 2014-08-23 12:00:00 - 2014-08-23 15:00:00
6 1 300 2014-08-23 15:00:00 - 2014-08-23 18:00:00
7 1 0 2014-08-23 18:00:00 - 2014-08-23 21:00:00
8 1 200 2014-08-23 21:00:00 - 2014-08-23 00:00:00
Run Code Online (Sandbox Code Playgroud)
这有可能与MySQL?
您可以在小时使用聚合和算术:
select floor(hour(time) / 3) as hourgroup, sum(points)
from pts
where status = 0 and user_id = 1 and
date(time) = "THIS DAY"
group by floor(hour(time) / 3);
Run Code Online (Sandbox Code Playgroud)
对于您的特定输出:
select (hour(time) div 3) as id, user_id, sum(points),
date('2014-08-23') + interval 3 * (hour(time) div 3) hour as starttime,
date('2014-08-23') + interval 3 * ((hour(time) div 3) + 1) hour as endtime
from pts
where status = 0 and user_id = 1 and
date(time) = date('2014-08-23')
group by floor(hour(time) / 3);
Run Code Online (Sandbox Code Playgroud)
计数为零的值存在问题.我不确定这些有多重要.您的查询会对数据进行调整,但不会旋转您想要的结果.
编辑:
如果你真的需要所有团队的时间,你可以这样做:
select n.n as id, user_id, sum(points),
date('2014-08-23') + interval 3 * n.n hour as starttime,
date('2014-08-23') + interval 3 * (n.n + 1) hour as endtime
from (select 0 as n union all select 1 union all select 2 union all select 3 union all
select 4 union all select 5 union all select 6 union all select 7
) n left join
pts
on n.n = hour(time) div 3
where status = 0 and user_id = 1 and
date(time) = date('2014-08-23')
group by n.n;
Run Code Online (Sandbox Code Playgroud)