I’m looking to order a log table so that it is grouped by id based on the first appearance of the id. In my example below, I have a table ‘test’ and I want to group the table by id so that all the ids are together, i.e. list all ‘623’ entries then all ‘444’ entries. I want the ‘623’ entries to come first because the first ‘623’ record came before the first ‘444’ entries.
Input:
╔═══════╦════════════╦═════╗
║ uid ║ time ║ id ║
╠═══════╬════════════╬═════╣
║ 001 ║ 01:45:10 ║ 623 ║
║ 002 ║ 02:45:20 ║ 444 ║
║ 003 ║ 03:45:30 ║ 444 ║
║ 004 ║ 04:45:40 ║ 623 ║
║ 005 ║ 05:45:50 ║ 623 ║
║ 006 ║ 06:45:00 ║ 444 ║
╚═══════╩════════════╩═════╝
Output:
╔═══════╦════════════╦═════╗
║ uid ║ time ║ id ║
╠═══════╬════════════╬═════╣
║ 001 ║ 01:45:10 ║ 623 ║
║ 004 ║ 04:45:40 ║ 623 ║
║ 005 ║ 05:45:50 ║ 623 ║
║ 002 ║ 02:45:20 ║ 444 ║
║ 003 ║ 03:45:30 ║ 444 ║
║ 006 ║ 06:45:00 ║ 444 ║
╚═══════╩════════════╩═════╝
The closest I’ve come is this:
select time, id from test group by id, time
╔═══════╦════════════╦═════╗
║ uid ║ time ║ id ║
╠═══════╬════════════╬═════╣
║ 002 ║ 02:45:20 ║ 444 ║
║ 003 ║ 03:45:30 ║ 444 ║
║ 006 ║ 06:45:00 ║ 444 ║
║ 001 ║ 01:45:10 ║ 623 ║
║ 004 ║ 04:45:40 ║ 623 ║
║ 005 ║ 05:45:50 ║ 623 ║
╚═══════╩════════════╩═════╝
But this isn’t exactly it because it’s ordering by the id. I’m not sure what the proper syntax is to have all the ‘623’ entries get listed first because the first ‘623’ record came before the first ‘444’ entry.
Thanks in advance for any help.
Got the answer:
SELECT test.time, test.id FROM
(
(SELECT DISTINCT id FROM test ORDER BY time ASC) as distinct_test
LEFT JOIN
test ON distinct_test.id = test.id
)
That makes sense now that I see it. Thanks everyone for the help.
Here is the code you need to use; I tested it on your data and it worked. It’s basically the same as Jason Swett’s, except you must use a
LEFT OUTER JOINrather than aRIGHT OUTER JOIN.