Creating min and max values and comparing them to timestamp values sql

Blake Steele :

I have a PostgreSQL database and I have a table that I am looking to query to determine which presses have been updated between the first cycle created_timestamp and the most recent cycle created_timestamp. Here is an example of the table, which is called event_log_summary.

press_id    cycle_number    created_timestamp
    1           1           2020-02-07 16:07:52
    1           2           2020-02-07 16:07:53
    1           3           2020-02-07 16:07:54
    1           4           2020-04-01 13:23:10
    2           1           2020-01-13 8:33:23
    2           2           2020-01-13 8:33:24
    2           3           2020-01-13 8:33:25
    3           1           2020-02-21 18:45:44
    3           2           2020-02-21 18:45:45
    3           3           2020-02-26 14:22:12

This is the query that I used to get me a three column output of press_id, mincycle, max_cycle, but then I want to compare the maxcycle created_timestamp to the mincycle created_timestamp and see if there is at least x amount of time between the two, say at least 1 day, I am unsure about how to implement that.

SELECT 
    press_id,
    MIN(cycle_number) AS minCycle,
    MAX(cycle_number) AS maxCycle
FROM
    event_log_detail
GROUP BY
    press_id

I have tried different things like using WHERE (MAX(cycle_number) - MIN(cycle_number > 1), but I am pretty new to SQL and don't quite fully know how to implement this. The output I am looking for, would have a difference of at least one day would be the following:

press_id
    1
    3

Presses 1 and 3 have their maximum cycle created_timestamp at least 1-day difference than their minimum cycle created_timestamp. I am just looking for the press_ids whose first cycle and the last cycle have a difference of at least 1 day, I don't need any other information on the output, just one column with the press_ids. Any help would be appreciated. Thanks.

a_horse_with_no_name :

You can use a HAVING clause:

select press_id, 
       max(created_timestamp) - min(created_timestamp) as diff
from event_log_detail
group by press_id
having max(created_timestamp) > min(created_timestamp) + interval '1 day';

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398654&siteId=1