This is my first question here. And I've been struggling for a while and I can't solve it.
So I want to get for all the circuits the location(latitude and longitude) to the most recent date.
The schema that I'm using contains important information so i will give an example:
table Circuit{
NR int Primary Key,
VEHICLE_ID int,
etc...
}
table StopPoints{
NR int Primary Key,
Circuit int Foreign Key Circuit.NR,
Latitude float,
Longitude float,
etc...
}
table StopPoint_Flux{
NR int Primary Key,
StopPoint int Foreign Key StopPoints.NR,
Date DATE,
etc...
}
And an example of the data in it:
Circuit:
| NR | VEHICLE_ID |
|---|---|
| 1 | 100 |
| 2 | 208 |
| 3 | 210 |
| 4 | 1 |
StopPoints:
| NR | Circuit | Latitude | Longitude |
|---|---|---|---|
| 1 | 1 | 0.3 | 5.0 |
| 2 | 1 | 1.7 | 8.0 |
| 3 | 2 | 7.0 | 10.0 |
| 4 | 4 | 11.0 | 1.2 |
| 5 | 3 | 45.0 | 46.0 |
| 6 | 4 | 43.1 | 6.23 |
| 7 | 1 | 34.42 | 36.98 |
| 8 | 3 | 40.48 | 47.50 |
StopPoint_Flux:
| NR | StopPoint | Date |
|---|---|---|
| 1 | 1 | 21/12/2020 |
| 2 | 2 | 19/12/2020 |
| 3 | 2 | 1/12/2020 |
| 4 | 1 | 5/12/2020 |
| 5 | 3 | 2/12/2020 |
| 6 | 5 | 7/12/2020 |
| 7 | 4 | 30/12/2020 |
| 8 | 5 | 7/12/2020 |
| 9 | 6 | 5/12/2020 |
| 10 | 8 | 1/12/2020 |
| 11 | 7 | 30/12/2020 |
| 12 | 6 | 8/12/2020 |
| 13 | 1 | 21/12/2020 |
The result that I need:
| VEHICLE_ID | Latitude | Longitude | Date |
|---|---|---|---|
| 100 | 34.42 | 36.98 | 30/12/2020 |
| 208 | 7.0 | 10.0 | 2/12/2020 |
| 210 | 45.0 | 46.0 | 7/12/2020 |
| 1 | 11.0 | 1.2 | 30/12/2020 |
CodePudding user response:
If ROW_NUMBER works.
SELECT
q.VEHICLE_ID
, q.Latitude
, q.Longitude
, q.Date
FROM
(
SELECT
circuit.VEHICLE_ID
, stop.Latitude
, stop.Longitude
, flux.Date
, ROW_NUMBER() OVER (PARTITION BY circuit.NR
ORDER BY flux.Date DESC, stop.NR) AS rn
FROM Circuit AS circuit
JOIN StopPoints AS stop
ON stop.circuit = circuit.NR
JOIN StopPoint_Flux AS flux
ON flux.StopPoint = stop.NR
) q
WHERE q.rn = 1
| vehicle_id | latitude | longitude | date |
|---|---|---|---|
| 100 | 34.42 | 36.98 | 2020-12-30 |
| 208 | 7 | 10 | 2020-12-02 |
| 210 | 45 | 46 | 2020-12-07 |
| 1 | 11 | 1.2 | 2020-12-30 |
db<>fiddle here
