I am creating a view that involves a little bit of fiddling with timestamps.
I have a table A with timestamps. The view will process the timestamps to see if each timestamp is within a certain range (9 AM - 5 PM). If the timestamp is within that range, I will fetch data matching the exact time in another table (B). Otherwise, I will fetch the next day (or this day's) first valid time (which is 9 AM) and the corresponding data from there.
Examples:
12/28/2012 17:01
-> fetch data from B for 12/29/2012 09:00
, set flag to after
. 12/28/2012 08:59
-> fetch data from B for 12/28/2012 09:00
, set flag to before
. 12/28/2012 09:55
-> fetch data from B for 12/28/2012 09:55
, set flag to null
. Here is what I have so far (not working, some in pseudocode). I mainly don't know how to set the flag based on the comparison and then, based on flag, perform next operation on b - all in one statement.
CREATE VIEW C as
SELECT time, (CASE WHEN (time< '9:00' ) THEN'before'
CASE WHEN(time> '17:00') THEN'after' else null END) AS flag FROM A
//These two should be combined into one create view statement
//The below is utterly wrong, I know, but explains what I mean
SELECT(
CASE WHEN (flag=='before') THEN SELECT * FROM B WHERE B.time = time set hour='9:00'
CASE WHEN(flag=='after') THEN SELECT* FROM B WHERE B.time = time + one day set hour='9:00'
ELSE SELECT* FROM B WHERE B.time = time ) as data
Tested using this fiddle: http://sqlfiddle.com/#!2/15be5/50
SELECT
q.time as original_time_check,
q.flag as flag_check,
case q.flag
when 'before' then q.NINE_AM_ON_THE_DAY
when 'after' then q.NINE_AM_THE_NEXT_DAY
else q.time
end as time
FROM
(
SELECT
time,
date(time) + INTERVAL 9 HOUR as NINE_AM_ON_THE_DAY,
date(time) + INTERVAL '1 9' DAY_HOUR as NINE_AM_THE_NEXT_DAY,
case
when time < (date(time) + INTERVAL 9 HOUR) then 'before'
when time < (date(time) + INTERVAL 17 HOUR) then 'in-range'
else 'after'
end as flag
FROM
Your_table
) q
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.