I have a table "Data" containing the columns "DateTimeUTC" and "A", where I want to calculate the difference in A over a certain time range and display this difference in a time series in Grafana.
This is how far I got:
SELECT
"DateTimeUTC" as "time",
"A"-(select "A" from "Data" WHERE "DateTimeUTC" <= "time" - interval ORDER BY "DateTimeUTC" Desc LIMIT 1)
FROM
"Data"
Unfortunately, this doesn't work yet. Here are my questions:
Thanks =) Sam
You can use a window function to do this:
CREATE TABLE public.data (
datetimeutc timestamp without time zone,
a integer
);
INSERT INTO public.data VALUES ('2024-05-14 14:00:00', 10);
INSERT INTO public.data VALUES ('2024-05-14 13:00:00', 12);
INSERT INTO public.data VALUES ('2024-05-14 12:00:00', 15);
INSERT INTO public.data VALUES ('2024-05-14 11:00:00', 8);
INSERT INTO public.data VALUES ('2024-05-14 10:00:00', 10);
WITH src AS(select datetimeutc as time, a, lag(a) OVER() as prev_a
FROM data ORDER BY datetimeutc desc)
SELECT time,a,a-prev_a
FROM src;
See the documentation for lag()
. The default offset is 1 which seems to be what you want.
Documentation for CTEs is here