3

This is probably not very correct title of the question, but failed to figure out better name.

I have following table structure:

id | lat  | lon  | trajectory_id | time
1  | 15.8 | 17.1 | 162           | 10:01
2  | 11.5 | 59.7 | 162           | 10:02
3  | 16.4 | 79.9 | 162           | 10:03
4  | 29.5 | 10.3 | 180           | 11:12
5  | 58.2 | 11.1 | 180           | 11:13
6  | 54.5 | 14.1 | 180           | 11:14
7  | 14.9 | 15.2 | 166           | 13:40
8  | 15.0 | 13.1 | 166           | 13:42

And I would like to get first point of each trajectory (ordered by time). This means following:

id | lat  | lon  | trajectory_id | time
1  | 15.8 | 17.1 | 162           | 10:01
4  | 29.5 | 10.3 | 180           | 11:12
7  | 14.9 | 15.2 | 166           | 13:40

How can I do that? I tried to group by trajectory_id and then applying limit 1, but it limits trajectories, not points itself.

3
  • 1
    Possible duplicate of Select first row in each GROUP BY group? Commented Dec 10, 2015 at 9:23
  • is it related to sql server or other database? Commented Dec 10, 2015 at 9:24
  • can't we use group by trajectory_id and order by time ? Commented Dec 10, 2015 at 9:26

2 Answers 2

4
WITH CTE AS
(SELECT id,lat,lon,trajectory_id,time,
ROW_NUMBER() OVER(PARTITION BY trajectory_id ORDER BY time) rn
FROM t)
SELECT id,lat,lon,trajectory_id,time FROM CTE WHERE rn=1
Sign up to request clarification or add additional context in comments.

Comments

3

Use ROW_NUMBER() per trajectory_id in order to only retrieve the first row per trajectory_id.

select id, lat, lon, trajectory_id, time
from
(
  select 
    mytable.*, 
    row_number() over (partition by trajectory_id order by time) as rn
  from mytable
) numbered
where rn = 1;

Comments

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.