我有一个带有 ids 和时间戳的表:
postgres=> select id_user, date_seconds from orders.orders order by id_user limit 10;
id_user | date_seconds
------------------------------+---------------------
00D4jzHHesfCXGO6VQfUun9JcCW2 | 2021-09-20 02:00:00
00D4jzHHesfCXGO6VQfUun9JcCW2 | 2021-10-06 02:00:00
00D4jzHHesfCXGO6VQfUun9JcCW2 |
00d9QGWjmbYdRTGw4h4GynhDp2K2 | 2021-10-01 02:00:00
00OI3ruCKeOFdIro11eVNcfp84A2 | 2021-10-06 02:00:00
00OI3ruCKeOFdIro11eVNcfp84A2 | 2021-08-24 02:00:00
00qwpdw23BSEBGkfJhR4Hb7Kg1v2 | 2021-09-17 02:00:00
00qwpdw23BSEBGkfJhR4Hb7Kg1v2 | 2021-09-20 02:00:00
00qwpdw23BSEBGkfJhR4Hb7Kg1v2 | 2021-10-04 02:00:00
00qwpdw23BSEBGkfJhR4Hb7Kg1v2 | 2021-08-20 02:00:00
(10 rows)
如您所见,一个id_user
可以在此表中出现多次。
我想按 对这张表进行分组id_user
。但是,我还希望在该特定的行之间获得列的平均增量时间。date_seconds
id_user
我想我可能需要使用LAG
psql 函数,但我不确定我如何或是否在正确的轨道上。
评论中建议的示例:
假设我有下表:
INSERT INTO orders(id_user, ordered_at) VALUES
('1', '2021-09-20 02:00:00'),
('1', '2021-10-06 02:00:00'),
('2', '2021-10-01 02:00:00'),
('3', '2021-10-06 02:00:00'),
('3', '2021-08-24 03:00:00'),
('4', '2021-08-20 02:00:00'),
('4', '2021-09-17 02:00:00'),
('4', '2021-09-20 02:00:00'),
('4', '2021-10-04 02:00:00');
期望的结果如下: 用户订单之间的平均时间可以计算如下: AVG( 订单之间的时间间隔 )
example: id_user 1: AVG( 2021-09-20 02:00:00 - 2021-10-06 02:00:00) which equals 16 days and 0 hours interval
example: id user 4: ACG( (2021-08-20 02:00:00 - 2021-09-17 02:00:00) , (2021-09-17 02:00:00 - 2021-09-20 02:00:00) , (2021-09-20 02:00:00 - 2021-10-04 02:00:00) )
example: id user 4: AVG( (interval '28 days') , (interval '3 days') , (interval '14 days') )
example: id user 4: 28+3+14 / 3 = 15 --> result should be interval '15 days'
postgres=> SELECT magic(ordered_at) as avg_timedelta, id_user from orders where id_user='4' group by id_user;
id_user | avg_timedelta
------------------------------+---------------------
4 | 15 days