Skip to content
Advertisement

Correct way to implement nested aggregation in PostgreSQL

I have a table that looks something like this:

Multiple foo_id can belong to bar_id, and multiple timestamp can belong to foo_id

What I want to do is to count the number of foo_id and the average length of foo_id (i.e. timestamp difference between the last and the first instance of the foo_id), belonging to the same bar_id.

I came up with this query, but it does not do the job:

I’ll be happy to hear any advise on how to do that correctly – I’m very new to SQL.

Cheers!

Advertisement

Answer

You can use sub-query as follows:

Demo db<>fiddle

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement