last()
Get the last value in one column when rows are ordered by another column
Since 0.0.11-beta
The last aggregate allows you to get the value of one column
as ordered by another. For example, last(temperature, time) returns the
latest temperature value based on time within an aggregate group.
Samples
Section titled “Samples”Get the temperature every 5 minutes for each device over the past day:
SELECT device_id, time_bucket('5 minutes', time) AS interval, last(temp, time)FROM metricsWHERE time > now () - INTERVAL '1 day'GROUP BY device_id, intervalORDER BY interval DESC;This example uses first and last with an aggregate filter, and avoids null values in the output:
SELECT TIME_BUCKET('5 MIN', time_column) AS interv, AVG(temperature) as avg_temp, first(temperature,time_column) FILTER(WHERE time_column IS NOT NULL) AS beg_temp, last(temperature,time_column) FILTER(WHERE time_column IS NOT NULL) AS end_tempFROM sensorsGROUP BY intervArguments
Section titled “Arguments”The syntax is:
SELECT last( value = <anyelement>, time = <anyelement>);| Name | Type | Default | Required | Description |
|---|---|---|---|---|
value | ANYELEMENT | - | ✔ | The value to return |
time | ”any” | - | ✔ | The timestamp to use for comparison. Accepts any comparable type such as TIMESTAMPTZ, TIMESTAMP, INTEGER, or BIGINT. |
Returns
Section titled “Returns”| Column | Type | Description |
|---|---|---|
last | ANY ELEMENT | The value from the value column corresponding to the latest time within the aggregate group. The return type matches the value input type. |