Skip to content
Advertisement

Postgres Select the first event for a user each day between a given time period

I would like to be able to get the first event for a user for each day between a given time period.

select  * from mytable
where eventId='123'and "time">'2020-02-11'  and "time"<'2020-02-14';

returns me this

table before

i would like To return this

table after

Any suggestions on how to attempt this

Update: I attempted the query and made a few changes based on the suggestion from @Gordon Linoff suggestion select distinct ("userId", "time"::date) from public.sensorevents t where "eventId" = '1cfb395f-8c05-4df9-8eed-b3e38edd623f' and"time" > '2020-02-11' and "time" < '2020-02-14';

This returns me the correct amount of rows 21 However i cant see the value
But if i add in the ,value select distinct ("userId", "time"::date),value from public.sensorevents t where "eventId" = '1cfb395f-8c05-4df9-8eed-b3e38edd623f' and"time" > '2020-02-11' and "time" < '2020-02-14';

to the query the query doesn’t seem to work and return me the 191 rows becuause each value is differnent

Advertisement

Answer

I would like to be able to get the first event for a user for each day between a given time period.

Use distinct on:

select distinct on (userid, "time"::date) *
from mytable t
where eventId = 123 and
      "time" > '2020-02-11' and
      "time" < '2020-02-14'
order by userid, "time"::date, "time";

Notes:

  • Do not use double quotes around column names. They just make queries harder to write and read.
  • Avoid using SQL keywords like time as column names.
  • I assume eventId is a number, so I dropped the single quotes.
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement