简体   繁体   中英

SQL query to iterate on a table to calculate the time difference between the 1st and 2nd record that have the same value in one of their fields?

I have a postgresql table storing posts from an online forum. Each post belongs to a thread. I want to calculate the time it takes for the post that starts a thread to get its first response (sometimes a thread never gets a response, so that has to be taken in to consideration)

The posts table has these fields:

post_id, post_timestamp, thread_id

There can be one or more posts per thread_id. This query, for example, returns the first and second post of a thread with id 1234:

select * from posts where thread_id = 1234 order by post_timestamp limit 2

I want to calculate the time difference between first and second post and store it in a separate table with these fields:

thread_id, seconds_between_1s_and_2nd
SELECT  (
        SELECT  post_timestamp
        FROM    posts
        WHERE   thread_id = t.id
        ORDER BY
                post_timestamp
        LIMIT 1 OFFSET 1
        ) - 
        (
        SELECT  post_timestamp
        FROM    posts
        WHERE   thread_id = t.id
        ORDER BY
                post_timestamp
        LIMIT 1 OFFSET 0
        )
FROM    threads t

, or, in PostgreSQL 8.4+ :

SELECT  (
        SELECT  post_timestamp - LAG(post_timestamp) OVER (ORDER BY post_timestamp)
        FROM    posts
        WHERE   thread_id = t.id
        ORDER BY
                post_timestamp
        LIMIT 1 OFFSET 1
        )
FROM    threads t

To express this in seconds, use EXTRACT(epoch FROM AGE(time1, time2))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM