更高效的查询来计算范围内值的组

时间:2016-10-04 19:19:05

标签: sql sqlite count group-by

我正在使用基本上看起来像这样的数据。

表:processed_data

sensor_id, reading, time_stamp
1,0.1,1234567890
1,0.3,1234567891
1,0.9,1234567892
1,0.32,1234567893
...

我想要做的是做一个查询,可以循环数据并计算每个类别中的读数。简单的例子,

类别(0-0.5,0.5-0.7,0.7-1)(我实际上计划将它们分成10个类别,但增量为0.1)。

这基本上就是我想要的,即使它不是有效的sql:

select count(reading between 0 and 0.5), count(reading between 0.5 and 0.7), count(reading between 0.7 and 1) from processed_data;

我能想到的唯一方法是做一个O * N操作,而不是一次循环。

select count(*) as low from processed_data where reading between 0 and 0.5
union 
select count(*) as med from processed_data where reading between 0.5 and 0.7 
union
select count(*) as high from processed_data where reading between 0.7 and 1;

我可能只是尝试在php中进行处理并扫描数据一次,但我更愿意让sql做,如果它足够智能。

1 个答案:

答案 0 :(得分:1)

您可以从值中派生类别,并将其用于分组:

SELECT CAST(reading * 10 AS INTEGER),
       COUNT(*)
FROM processed_data
GROUP BY CAST(reading * 10 AS INTEGER);