I have the following data in one table:
Time, Type, Kilometers
12:00, 1, 0.1
12:30, 2, 0.2
14:00, 1, 0.4
15:00, 2, 1.0
16:00, 1, 1.2
16:30, 2, 1.5
16:45, 1, 2.0
This data is sorted chronologically using the DateTime field. I would like to show these record ‘pairs’ as 1 row, like so:
StartTime, Type1Km, Type2Km
12:00, 0.1, 0.2
14:00, 0.4, 1.0
16:00, 1.2, 1.5
16:45, 2.0, NULL
There are a couple of caveats: If there is no Type1 to start, then show NULL in the resulting tables’ Type1Km field. Similarly, if there is no Type2 end, show NULL in records’ Type2Km field.
How could i do this?
Unfortunately, MySQL lacks a
FULL OUTER JOIN, so you’ll have toUNIONtwo sets together.This will get you the cases where
Type1Kmexists, whether or notType2Kmdoes.Now we need the cases where
Type1Kmdoes not exist.UNIONthose together, and you have the desired result:Update
In my previous query, I forgot to account for having a “type 2” record at the very beginning. Updated to account for that. Here’s the results I get:
Data in
timestable:Results of query: