0

I've used WINDOW functions before but only when working with data that has a fixed cadence/interval. I am likely missing something simple in aggregation but I've never had a scenario where I'm not working with fixed intervals.

I have a table the records samples at arbitrary timestamps. A sample is only recorded when it is a delta from the previous sample and the sample rate is completely irregular due to a large number of conditions. The table is very simple:

id (int) 
happened_at (timestamp)
sensor_id (int)
new_value (float)

I'm trying to construct a query that will include a count of all of the samples before the happened_at of a given result row. So given an ultra simple 2 row sample data set:

id|happened_at     |sensor_id| new_value
1 |2019-06-07:21:41|134679   | 123.331
2 |2019-06-07:19:00|134679   | 100.009

I'd like the result set to look like this:

happened_at     |sensor_id | new_value | sample_count
2019-06-07:21:41|134679    |123.331    |2
2019-06-07:19:00|134679    |123.331    |1

I've tried:

SELECT *,
       (SELECT count(sample_history.id) OVER (PARTITION BY score_history.sensor_id 
        ORDER BY sample_history.happened_at DESC))
FROM sensor_history
ORDER by happened_at DESC

and the duh not going to work.

(SELECT count(*) 
FROM sample_history
WHERE sample_history.happened_at <= sample_timestamp)

Insights greatly appreciated.

1 Answer 1

1

Get rid of the SELECT (sub-query) when using the window function.

SELECT *,
       count(*) OVER (PARTITION BY sensor_id ORDER BY happened_at DESC)
FROM sensor_history
ORDER BY happened_at DESC
Sign up to request clarification or add additional context in comments.

1 Comment

One note it seems that I need the PARTITION BY ORDER BY to be happened_at ASC not DESC to get the correct calculation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.