Home > Software engineering >  postgresql request to get first occurence of a repeated value
postgresql request to get first occurence of a repeated value

Time:09-23

I am trying to get the first occurence of when the position of one of my items is equel to AL, here's an example of what I mean:

id  | msr_id | user_id |            date            | pos | 
------ -------- --------- ---------------------------- ----- 
  210 |     38 |      58 | 2018-06-12 08:53:41.929181 | AL  |
  211 |     38 |      58 | 2018-06-12 08:56:37.223835 | AL  |
  212 |     36 |      56 | 2018-06-12 08:57:35.010093 | AR  |
  213 |     38 |      58 | 2018-06-12 09:00:54.841769 | AL  |
  214 |     36 |      56 | 2018-06-12 09:02:13.51732  | RR  |

this is my table and, if you look at the example you can see that when msr_id is equal to 38, I have multiple passages in the AL position, I want to be able to get the first one of those passages, in this example the one where the actual id is equal to 210, if anyone can help it would be greatly appreciated, thanks!

CodePudding user response:

select id,msr_id from your_table where pos='AL' 
order by date asc
limit 1

CodePudding user response:

You can use distinct on:

select distinct on (msr_id) t.*
from t
where pos = 'AL'
order by msr_id, date;
  • Related