How to sort an event table by time (have different timezones)?
I have a table that is structured the following way (that i can't change):
EventName, LocalTime, Timezone
Data would be something like this:
Event1, 10:00, ET
Event2, 11:00, ET
Event3, 12:00, ET
Event4, 10:00, CT
how can i write a sql to sort this by actual time so result would be like:
Event1, 10:00, ET
Event2, 11:00, ET
Event4, 10:00, CT
Event3, 12:开发者_运维知识库00, ET
Note that Event2 and Event4 happen at the same time so whichever comes first doesn't matter.
My database is MySQL.
Again, I can not modify the source so I have to work with the data I'm dealt with
Thanks
Using a modern ver of mysql...
Create table Tz_offsets:
col Timezone, offset
Data:
ET, 0
CT, 1
Select EventName, LocalTime, Timezone
From my_data_table
JOIN Tz_offsets On Tz_offsets.Timeszone = my_data_table.Timeszone
Where xxx
Order By (LocalTime - offset)
The key here is that Order By can take an expression.
See http://dev.mysql.com/doc/refman/5.5/en/select.html
Optimization
In the above example, MySql will create a temp table. Depending on the size of your data, it might be much faster to pay a data insertion price vs a data retrieval price.
To do so: add another column to the data table, "time_gmt" and then sort on the new column. But if you can't, the above will work.
If you can't add the Tz_offsets table (if you can only use raw sql), then you have two choices:
Add the Tz_offsets table as a temp table each time you run your sql. Your MySQL user will need temp table create permission.
Do the tz offset lookups within the order by expression by using Case expression.
Eg
Select EventName, LocalTime, Timezone
From my_data_table
Where xxx
Order By (LocalTime -
(CASE Timezone WHEN 'ET' THEN 0 WHEN 'CT' THEN 1 WHEN 'PT' THEN 3 ELSE 0))
精彩评论