3

I've got this query:

SELECT apple, banana, update_at FROM 
(
    SELECT DISTINCT ON (apple) *
        FROM table
            WHERE apple IN ('ad', 'sa')

        ORDER BY apple, update_at DESC
) q

The purpose of this query is to get the rows that has apple "ad" or "sa", and return the most updated row (update_at (timestamp)). This query works.

My problem is that I want that instead of the update_at column, the query will show the difference between the timestamps (duration) of the query matched row and the row which preceded it.

Example:

apple---|banana---|update_at
============================
ad------|VAL------|2017-06-01 12:12:30
ad------|VAL------|2017-06-01 09:00:00
ad------|VAL------|2017-05-31 13:41:00

Result:

apple---|banana---|update_at
============================
ad------|VAL------|**03:12:30**

03:12:30 is the duration.

Hope that it clear enough.

1 Answer 1

3

You need to use window functions for this:

SELECT apple, 
       banana, 
       update_at, 
       prev_update_at, 
       update_at - prev_update_at as duration
FROM (
   SELECT *, 
          row_number() over (partition by apple order by update_at desc) as rn, 
          lag(update_at) over (partition by apple order by update_at) as prev_update_at
   FROM table
   WHERE apple IN ('ad', 'sa')
) q
where rn = 1;
Sign up to request clarification or add additional context in comments.

1 Comment

@RonZ: sorry, wrong order by for the lag() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.