1

I just want to filter few columns from the table according to MAX(ts). ts = timestamp. And everything is OK if I select only two columns - deviceid and ts:

SELECT deviceid, MAX(ts) 
FROM device_data 
GROUP BY deviceid

and the result:

enter image description here

but I also need two columns more - longitude and lattitude. I have the problem if I select longitude and lattitude because they have to appear in GROUP BY and I get too much results with the same deviceid:

enter image description here

How can I avoid inserting longitude and lattitude in GROUP BY?

2 Answers2

1

There are several solutions for this. One is to use window functions to get the first longitude, latitude, ...etc within a partition of same deviceid when ordered by descending date.

Then you will get duplicates, which you can remove with distinct:

SELECT DISTINCT deviceid, 
       FIRST_VALUE(longitude) OVER win AS longitude,
       FIRST_VALUE(latitude) OVER win AS latitute,
       FIRST_VALUE(ts) OVER win AS ts 
FROM   device_data
WINDOW win AS (PARTITION BY deviceid ORDER BY ts DESC);
trincot
  • 317,000
  • 35
  • 244
  • 286
1

You can create a table that contains device_id and max of ts per device_id, then do an inner join with original device_data to get desired result.

Unless you have multiple rows with same device_id and max(ts), this should work.

SELECT a.deviceid, a.ts, a.longitude, a.lattitude
FROM device_data a
INNER JOIN
(SELECT deviceid, MAX(ts) as max_ts
FROM device_data 
GROUP BY deviceid) b ON a.ts = b.max_ts
GROUP BY 1,2,3,4;
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
penguin
  • 1,267
  • 14
  • 27