til icon indicating copy to clipboard operation
til copied to clipboard

Đếm số event xuất hiện mỗi phút trong SQL

Open xluffy opened this issue 7 months ago • 0 comments

SELECT date_trunc('minute', TO_TIMESTAMP(created_at)) AS minute, 
COUNT(DISTINCT player_id) AS CCU
FROM raw_events 
GROUP BY 1
ORDER BY COUNT(DISTINCT player_id) DESC LIMIT 10;
  • date_trunc sẽ "làm tròn" dữ liệu về một đơn vị, ví dụ phút 23 nhưng bất kể giây bao nhiêu cũng sẽ làm tròn về giây 23
  • Sau đó có thể GROUP BY theo từng mốc phút để tính ra số event xuất hiện trong mỗi phút
# SELECT date_trunc('minute', '2024-06-26 13:23:10+00'::timestamp);
     date_trunc
---------------------
 2024-06-26 13:23:00
(1 row)

# SELECT date_trunc('minute', '2024-06-26 13:23:59+00'::timestamp);
     date_trunc
---------------------
 2024-06-26 13:23:00
(1 row)

# SELECT date_trunc('minute', '2024-06-26 13:23:44+00'::timestamp);
     date_trunc
---------------------
 2024-06-26 13:23:00
(1 row)

# SELECT date_trunc('minute', '2024-06-26 13:23:01+00'::timestamp);
     date_trunc
---------------------
 2024-06-26 13:23:00
(1 row)

xluffy avatar Jun 27 '24 03:06 xluffy