0

你好,

我试图找出一种将记录分组为某些块的有效方法。记录由计数和时间组成,请参见下面的示例。每分钟进行一次计数。

+----------+---------------+---------------+
| count_id | count_reading | count_time    |
+----------+---------------+---------------+
| 5847348  | 168           | 1358174236000 |
+----------+---------------+---------------+
| 5847347  | 342           | 1358174176000 |
+----------+---------------+---------------+
| 5847346  | 228           | 1358174116000 |
+----------+---------------+---------------+
| 5847345  | 240           | 1358174056000 |
+----------+---------------+---------------+
| 5847344  | 12            | 1358173996000 |
+----------+---------------+---------------+
| 5847343  | 0             | 1358173936000 |
+----------+---------------+---------------+
| 5847342  | 48            | 1358173876000 |
+----------+---------------+---------------+
| 5847341  | 480           | 1358173816000 |
+----------+---------------+---------------+
| 5847340  | 473           | 1358173756000 |
+----------+---------------+---------------+
| 5847339  | 380           | 1358173696000 |
+----------+---------------+---------------+

我想要实现的是各个班次的计数总和,我有两种情况我被困在......

  • 从 0700-1900 和 1900-0700 运行的 12 小时班次的总和。
  • 运行 0700-1400、1400-2200 和 2200-0700 的班次的总和。

结果看起来像:

+---------------+--------------------------------------------+
| count_reading | count_time                                 |
+---------------+--------------------------------------------+
| 10000         | Between 0700 and now starting on the 13th  |
+---------------+--------------------------------------------+
| 20000         | Between 1900 and 0700 starting on the 12th |
+---------------+--------------------------------------------+
| 50000         | Between 0700 and 1900 starting on the 12th |
+---------------+--------------------------------------------+
| 10000         | Between 1900 and 0700 starting on the 11th |
+---------------+--------------------------------------------+

我正在处理两个查询,这些查询将根据场景解决上述问题。我已经四处寻找帮助,但运气不佳,如果有人能够帮助我,将不胜感激。

4

1 回答 1

1

group by可以采用任意子句和派生值,例如(在伪代码中):

SELECT SUM(count_reading), TIME(count_time) BETWEEN 7 and 19 AS shift
GROUP BY shift

您最终会得到两组 - shift = 17-19 和shift = 019-7`

类似地,对于 3 向移位,还有一点逻辑:

SELECT sum(count_reading),
    CASE WHEN TIME(count_time) BETWEEN 7 AND 14 THEN 1 ELSE
         WHEN TIME(count_time) BETWEEN 14 and 22 THEN 2
         ELSE 3 END AS shift
GROUP BY shift

实际的逻辑/sql 语法应该非常简单。

于 2013-01-14T15:30:15.367 回答