我有一张桌子,里面有几个小时和那些小时的值。例如:
Hour Value1 Value2
9 100 1
10 170 4
11 30 17
12 144 59
13 6 1
.
.
.
23 204 8
我需要计算每列的Value1和Value2,但是需要指定的时间段(间隔)。
例如:
00-09h Value1 = 100, Value2 = 1
09-11h Value1 = 300, Value2 = 22
11-13h Value1 = 180, Value2 = 77
13h-21h Value1 = ..., Value2 = ...
我能想到的是为每个间隔创建数组,然后用循环填充它们(检查值是否属于该间隔,然后将其推送到数组)。
但是有更方便有效的方法吗?使用Query?
答案 0 :(得分:2)
您可以动态创建包含范围的派生表,并将其与表格连接:
select s.*, sum(t.Value1) as Value1, sum(t.Value2) as Value2
from (
select 0 as start, 9 as end union all
select 9 as start, 11 as end union all
select 11 as start, 13 as end union all
select 13 as start, 21 as end
) s
join your_table t on t.Hour between s.start and s.end
group by s.start, s.end
答案 1 :(得分:2)
使用sum()
和whereBetween()
:
$model = Model::all();
$totalValue1=$model->whereBetween('hour',[9,11])->sum('value1');
$totalValue2=$model->whereBetween('hour',[9,11])->sum('value2');
$totalValue1=$model->whereBetween('hour',[11,13])->sum('value1');
$totalValue2=$model->whereBetween('hour',[11,13])->sum('value2');
$totalValue1=$model->whereBetween('hour',[13,21])->sum('value1');
$totalValue2=$model->whereBetween('hour',[13,21])->sum('value2');