开发者

SQL QUERY - Time comparison (SQLite)

开发者 https://www.devze.com 2023-04-07 08:48 出处:网络
I would like to ask if someone would be able to help with sql query. I have table with times in 开发者_运维百科format: HH:MM:SS. I want to write a query that returns me the closest time (to the future

I would like to ask if someone would be able to help with sql query. I have table with times in 开发者_运维百科format: HH:MM:SS. I want to write a query that returns me the closest time (to the future) to the current time. For example: Table contains 3 rows: 12:00:00, 12:01:00, 12:02:00. If:

1) Current time is: 12:00:30. The query returns: 12:01:00., etc.

BUT!

2) Current time is: 12:02:30. The query returns: 12:00:00.

I write this query, whitch solves me 1), but not 2).

select time(myColumn) 
from myTable 
where time(myColumn) >= time(current_timestamp, 'localtime') 
order by myColumn 
limit 1

I would appreciate if someone could help.

PS: Database is in SQLite (must be) and is not possible to calculate with dates eg: 2011-01-01 12:00:00...)

Thank you Tom.


You could do this:

             select min(  time(yourtimecolumn) ) from foo
             where time(current_timestamp, 'localtime') < time(yourtimecolumn) 

Edited by Tom


EDIT: if you need to get the NEXT closest time, try:

SELECT time(myColumn)
FROM myTable
ORDER BY CASE WHEN myColumn - time(current_timestamp, 'localtime') > 0,
         THEN myColumn - time(current_timestamp, 'localtime')
         ELSE myColumn - time(current_timestamp, '24 hours', 'localtime')
         END CASE
LIMIT 1

It sorts by the amount of time to the next timestamp in the database, attempting to add 24 hours if necessary to get a positive number (an upcoming time) as a result.


I solved it! This is the query:

select 
case when 
(select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) is null 
then 
(select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') > time(myColumn)) 
else 
(select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) 
end

Thx Tim & Dave who showed me the way.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号