【问题标题】:Split rows into m parts and build the average of each part [SQLite]将行拆分为 m 个部分并构建每个部分的平均值 [SQLite]
【发布时间】:2016-10-01 18:24:51
【问题描述】:

我遇到了以下问题。

给定一个基本上由两列组成的表,一个时间戳和一个值,我需要通过对值和时间戳取平均值,将时间戳之间的 n 行减少到 m 个数据行。

假设我想要 15 到 85 之间的所有数据,最多包含 3 个数据行。

time | value
10   | 7
20   | 6
30   | 2
40   | 9
50   | 4
60   | 3
70   | 2
80   | 9
90   | 2

Remove unneeded rows and split them into 3 parts

20   | 6
30   | 2

40   | 9
50   | 4
60   | 3

70   | 2
80   | 9

Average them

25   | 4
50   | 8
75   | 5.5

我知道如何通过包含 WHERE 来删除不需要的行,如何平均给定的一组行,但想不出如何将所需的数据集分成 m 个部分。

感谢任何帮助和想法!

我使用 SQLite,这并没有让这变得更容易,而且很遗憾不能切换到任何其他方言。

我尝试根据行数和行数对行进行分组,但没有成功。我想到的唯一其他解决方案是获取受影响的行数和具有限制和偏移量的 UNION m SELECT。

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    我已经开始工作了。我的问题是我不小心做了整数除法。

    我用来分组项目的公式是:

    group = floor ( row_number / (row_count / limit) )
    

    完整的 SQL 查询如下所示:

    SELECT
        avg(measurement_timestamp) AS measurement_timestamp,
        avg(measurement_value) AS average
    FROM (
         SELECT
              (SELECT COUNT(*)
                   FROM measurements_table
                        WHERE measurement_timestamp > start_time AND measurement_timestamp < end_time)
               AS row_count,
    
               (SELECT COUNT(0)
                    FROM measurements_table t1
                         WHERE t1.measurement_timestamp < t2.measurement_timestamp
                         AND t1.measurement_timestamp > start_time AND t1.measurement_timestamp < end_time
                         ORDER BY measurement_timestamp ASC )
               AS row_number,
    
               *
               FROM measurements_table t2
               WHERE t2.measurement_timestamp > start_time AND t2.measurement_timestamp < end_time
               ORDER BY measurement_timestamp ASC)
    GROUP BY CAST((row_number / (row_count / ?)) AS INT)
    
    * the limit has to be a float
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2018-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多