简体   繁体   中英

Postgres min/max per hour

Hi I have a table name token which will have data of token generated like this

id     | generated_time          | token_name
461087 | 2016-10-21 09:02:53.951 |  G1  
461088 | 2016-10-21 09:31:13.469 |  C1
461089 | 2016-10-21 09:31:15.711 |  C2  
461090 | 2016-10-21 10:37:17.73  |  C3
461091 | 2016-10-21 10:02:53.951 |  G2  
461092 | 2016-10-21 10:15:13.469 |  C4
461093 | 2016-10-21 11:22:15.611 |  C5  
461094 | 2016-10-21 11:31:14.743 |  C6

and table token_queue like this which have one to one relation

serving_end_time        |  serving_start_time      | token_id
2016-10-21 09:04:45.681 |  2016-10-21 09:03:49.05  | 461087 
2016-10-21 09:33:49.035 |  2016-10-21 09:32:07.996 | 461088 
2016-10-21 09:34:42.431 |  2016-10-21 09:32:27.134 | 461089 
2016-10-21 10:39:57.775 |  2016-10-21 10:38:37.428 | 461090
2016-10-21 10:04:49.715 |  2016-10-21 10:03:09.972 | 461091
2016-10-21 10:17:28.268 |  2016-10-21 10:16:06.946 | 461092
2016-10-21 11:23:36.036 |  2016-10-21 11:22:30.233 | 461093
2016-10-21 11:32:32.876 |  2016-10-21 11:31:27.044 | 461094

now I want to show the min/max of the whole day -24hrs (current_date) in per hour basis from token table and calculate min/max from token_queue ie

MIN(token_queue.serving_end_time - token_queue.serving_start_time)
MAX(token_queue.serving_end_time - token_queue.serving_start_time)

here is the sample output for date 2016-10-21

    hour                | min         | max
    2016-10-21 09:00:00 | 00:01:06    | 00:05:00
    2016-10-21 10:00:00 | 00:01:16    | 00:04:00
    2016-10-21 11:00:00 | 00:02:00    | 00:05:26

thank you for your any help/suggestion.

SELECT date_trunc('hour', t.generated_time) AS hour,
       min(tq.serving_end_time - tq.serving_start_time) AS min,
       max(tq.serving_end_time - tq.serving_start_time) AS max
FROM token t
     JOIN token_queue tq
        ON t.id = tq.token_id
GROUP BY 1
ORDER BY 1;

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