Skip to Content
TORMAggregates and time buckets

Aggregates and time buckets

On this page

OrmClient executes counts, numeric aggregates and time-bucket downsampling in the database. The example uses TORM and TORM.Sqlite; see QuestDB, TDengine and IoTDB for separate time-series clients.

Run a time-bucket query

Create the console project and install both packages as shown in the quick start, then replace Program.cs with this code. It uses in-memory SQLite, aggregates two minutes of samples and releases the database on exit.

using System.Globalization; using TORM; await using var db = new OrmClient(new ConnectionConfig { DatabaseType = DatabaseType.Sqlite, ConnectionString = "Data Source=:memory:" }); await db.CodeFirst!.InitTableAsync<TelemetryPoint>(); var origin = new DateTime(2026, 1, 1, 0, 0, 0, DateTimeKind.Utc); var end = origin.AddMinutes(2); await db.InsertableRange(new[] { new TelemetryPoint { Id = 1, Timestamp = origin.AddSeconds(10), Value = 10, State = true }, new TelemetryPoint { Id = 2, Timestamp = origin.AddSeconds(20), Value = 30, State = false }, new TelemetryPoint { Id = 3, Timestamp = origin.AddSeconds(70), Value = 50, State = true } }).ExecuteAsync(); var buckets = await db.Queryable<TelemetryPoint>() .Where(x => x.Timestamp >= origin && x.Timestamp < end) .ToTimeBucketListAsync(x => x.Timestamp, x => x.Value, x => x.State, new OrmTimeBucketQuery { Origin = origin, BucketMilliseconds = 60_000, Aggregation = OrmTimeBucketAggregation.Average, Take = 10 }); foreach (var bucket in buckets) { Console.WriteLine($"{bucket.BucketIndex}: {bucket.Value.ToString(CultureInfo.InvariantCulture)}, {bucket.State}"); } /// <summary>时间、数值与质量状态共同组成一条采样记录。</summary> [OrmTable("telemetry_points")] public sealed class TelemetryPoint { /// <summary>采样记录的唯一主键,由示例显式赋值。</summary> [OrmColumn(IsPrimaryKey = true)] public long Id { get; set; } /// <summary>采样时间,本示例始终写入 UTC 值。</summary> [OrmColumn(IsNullable = NullableState.Nullable)] public DateTime Timestamp { get; set; } /// <summary>使用浮点列保留平均值的小数部分。</summary> [OrmColumn(IsNullable = NullableState.Nullable)] public double Value { get; set; } /// <summary>采样质量标记,数值统计不会自动排除 false 记录。</summary> [OrmColumn(IsNullable = NullableState.Nullable)] public bool State { get; set; } }

Expected output:

0: 20, False 1: 50, True

This example uses non-null samples; nullable samples require explicit filtering and null-handling rules.

Parameters and results

MemberMeaning
OriginTime reference for bucket zero; it does not add a query time range
BucketMillisecondsPositive integer milliseconds; one minute is 60_000
AggregationAverage, Minimum, Maximum, First or Last
TakePositive result-bucket limit, not a limit on scanned source rows
BucketIndexZero-based index relative to Origin; results are sorted by this index
Value / StateAggregated value and quality state

Reconstruct a bucket’s start with origin.AddMilliseconds(bucket.BucketIndex * 60_000d). Empty buckets are not automatically filled with zero or interpolated. Applications must choose how to represent missing chart samples.

Each selector targets one mapped property. Use a consistent time basis and an explicit Where time range. If a table contains multiple measurement identities, also filter the identity; otherwise their records share the same buckets.

Aggregation and state

AggregationValueState
Average / Minimum / MaximumAverage / minimum / maximum of participating recordsTrue only if every participating record is true
First / LastValue of the earliest / latest recordState of the selected record

False-state records still contribute numeric values. Add .Where(x => x.State) to aggregate valid samples only. First and Last currently order only by timestamp; equal timestamps have no additional primary-key tie-breaker.

The entry point preserves the table, shard range and filters, and defines its own bucket ordering. Restrict the shard range before aggregation. Records are combined across physical tables before bucketing; this is not an unweighted average of per-table averages.

Ordinary numeric aggregates

Using the same db and TelemetryPoint:

var count = await db.Queryable<TelemetryPoint>().CountAsync(); var maximum = await db.Queryable<TelemetryPoint>().MaxAsync(x => x.Value); var minimum = await db.Queryable<TelemetryPoint>().MinAsync(x => x.Value); var sum = await db.Queryable<TelemetryPoint>().SumAsync(x => x.Value); Console.WriteLine($"Count={count}; Max={maximum}; Min={minimum}; Sum={sum}");

The example returns Count=3; Max=50; Min=10; Sum=90. Each terminal method performs a separate database operation. Use supported transaction isolation when you need a consistent read view, and keep operations sequential on one client.

Source: TORM/src/TORM/Queryable/OrmTimeBucketQuery.cs and OrmQueryableProvider.TimeBucket.cs.