Given the table (hypertable) with the columns peripheral (FK), data point type (FK), time and value, can the peripheral and/or data point type be included with each maximum aggregate? Can the top n (like top 3) FKs be included?
Table "public.iot_datapoint"
Column | Type
--------------------+--------------------------
time | timestamp with time zone
value | double precision
data_point_type_id | uuid
peripheral_id | uuid
-- Current query
SELECT time_bucket('60.000s', "time") AS "time_bucket",
MAX(iot_datapoint.value) AS "0"
FROM iot_datapoint
WHERE (peripheral_id IN (...)
AND data_point_type_id IN (...)
AND TIME >= %(A0)s
AND TIME < %(A1)s)
GROUP BY 1
ORDER BY 1
-- Tried query
SELECT time_bucket('60.000s', "time") AS "time_bucket",
MAX(iot_datapoint.value) AS "0", peripheral_id
FROM iot_datapoint
WHERE (peripheral_id IN (...)
AND data_point_type_id IN (...)
AND TIME >= %(A0)s
AND TIME < %(A1)s)
GROUP BY 1, peripheral_id
ORDER BY 1
Adding peripheral_id
in the SELECT
requires it to be added to the GROUP BY
but that prevents the maximum being returned for the whole time bucket.
-- Current result
time_bucket | 0
------------------------+---------------
2024-06-04 16:21:00+00 | -2
2024-06-04 16:22:00+00 | -0.4
-- Tried result
time_bucket | 0 | peripheral_id
------------------------+---------------+--------------------------------------
2024-06-04 16:21:00+00 | -1 | b319b263-0526-4a26-b71a-39553869b2a0
2024-06-04 16:21:00+00 | -2 | 894b4df3-ec52-4358-b8fa-d2bbece6e8ff
2024-06-04 16:22:00+00 | -0.4 | b319b263-0526-4a26-b71a-39553869b2a0
2024-06-04 16:22:00+00 | 1.234 | 894b4df3-ec52-4358-b8fa-d2bbece6e8ff
-- Ideal result (top 1 FK)
time_bucket | 0 | max_1_peripheral_id
------------------------+---------------+--------------------------------------
2024-06-04 16:21:00+00 | -2 | 894b4df3-ec52-4358-b8fa-d2bbece6e8ff
2024-06-04 16:22:00+00 | -0.4 | b319b263-0526-4a26-b71a-39553869b2a0
-- Ideal result (top 2 FK)
time_bucket | 0 | max_1_peripheral_id | max_2_peripheral_id
------------------------+---------------+--------------------------------------+--------------------------------------
2024-06-04 16:21:00+00 | -2 | 894b4df3-ec52-4358-b8fa-d2bbece6e8ff | b319b263-0526-4a26-b71a-39553869b2a0
2024-06-04 16:22:00+00 | -0.4 | b319b263-0526-4a26-b71a-39553869b2a0 | 894b4df3-ec52-4358-b8fa-d2bbece6e8ff