Question

I have a PL/SQL table with two columns: log_date (DATE) and value (FLOAT). The data is very fine-grained, the difference between log_dates could be a few milliseconds. The value changes over time. I want to find, using SQL, the maximum and minimum amount of time between log_dates it takes for value to increase.

Edit: Example

log_date | value
-------------------  
  15:00  |  10
  15:01  |  10
  15:02  |  11
  15:03  |  11
  15:04  |  11
  15:05  |  11
  15:06  |  12

Between 15:00 and 15:02 value increased BUT it also increased between 15:03 and 15:06 which took longer, and so I want a query that would return (in this case) '3 minutes' (as a DATE or a NUMBER) - the longest amount of time it took for value to increase.

Was it helpful?

Solution

I can give you an answer in T-SQL, but I'm not sure what dialect you're using. TBH, a loop here is the first thing that springs to mind (someone else may have a better way of doing it!):

DECLARE @temp TABLE ( log_date DATETIME, value FLOAT )
INSERT INTO @temp ( log_date, value ) SELECT log_date, value FROM <MyTableName>

DECLARE @diff TABLE ( time_diff INT, old_value FLOAT, new_value FLOAT )

-- the loop

DECLARE @prev_value FLOAT, 
        @cur_value FLOAT,
        @prev_log_date DATETIME,
        @cur_log_date DATETIME

WHILE EXISTS ( SELECT NULL FROM @temp )
BEGIN

    SELECT TOP 1 @cur_log_date = log_date, @cur_value = value
    FROM @temp
    ORDER BY log_date

    IF ( @prev_value IS NOT NULL AND @prev_log_date IS NOT NULL )
    BEGIN

        INSERT INTO @diff ( time_diff, old_value, new_value )
        SELECT DATEDIFF('ms', @prev_log_date, @cur_log_date ),
               @prev_value, @cur_value

    END

    SELECT @prev_log_date = @cur_log_date, @prev_value = @cur_value
    DELETE FROM @temp WHERE log_date = @cur_log_date

END

SELECT MAX(time_diff), MIN(time_diff) FROM @diffs

This way, you end up with a table of all differences that you can then query.

HTH

OTHER TIPS

You can use this query to find the max and min log_date for a specific value. But for this you will have to specify the value. You might have to modify the query a little if you want to make it more generic

SELECT MAX(log_dates) AS MaxLogDate, MIN(log_dates) AS MinLogDate 
  FROM yourtable 
 WHERE <ANY condition IF needed> 
 GROUP 
    BY VALUE 
HAVING VALUE = <specify VALUE>;

Try something like the following:

select top 1 * from
(
  select 
    max(log_date) - min(log_date) as duration,
    value
  from logdata
  group by value
)
order by duration asc

and change the asc to desc for the other value.

[edit] I can't actually test this at the moment, so I'm not sure if the max-min will work, you can use the datediff function posted in one of the other answers as an alternative if this fails. [/edit]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top