请提供一些建议,以便在postgres中使用窗口函数来解决下面的问题。
输入数据:
111;“2016-01-01 10:00:00”;“park”
111;“2016-01-01 10:01:00”;“指南”
111;“2016-01-01 10:02:00”;“指南”
111;“2016-01-01 10:03:00”;“操作”
111;“2016-01-01 10:04:00”;“指南”
111;“2016-01-01 10:05:00”;“指南”
222;“2016-01-01 10:00:00”;“park”
222;“2016-01-01 10:01:00”;“指南”
222;“2016-01-01 10:02:00”;“指南”
222;“2016-01-01 10:03:00”;“操作”
222;“2016-01-01 10:04:00”;“指南”
222;“2016-01-01 10:05:00”;“指南”
需要输出:
111;“2016-01-01 10:00:00”;“park”; 1
111;“2016-01-01 10:01:00”;“指南”; 2
111;“2016-01-01 10:02:00”;“指南”; 2
111;“2016-01-01 10:03:00”;“操作”; 3
111;“2016-01-01 10:04:00”;“指南”; 4
111;“2016-01-01 10:05:00”;“指南”; 4
222;“2016-01-01 10:00:00”;“park”; 1
222;“2016-01-01 10:01:00”;“指南”; 2
222;“2016-01-01 10:02:00”;“指南”; 2
222;“2016-01-01 10:03:00”;“操作”; 3
222;“2016-01-01 10:04:00”;“指南”; 4
222;“2016-01-01 10:05:00”;“指南”; 4
输入数据的代码:
创建临时表input_tb(id int,日期时间戳,类别文本);
插入input_tb值(111,'2016-01-01:10:00:00','park');
插入input_tb值(111,'2016-01-01:10:01:00','guide');
插入input_tb值(111,'2016-01-01:10:02:00','guide');
插入input_tb值(111,'2016-01-01:10:03:00','操作');
插入input_tb值(111,'2016-01-01:10:04:00','guide');
插入input_tb值(111,'2016-01-01:10:05:00','guide');
插入input_tb值(222,'2016-01-01:10:00:00','park');
插入input_tb值(222,'2016-01-01:10:01:00','guide');
插入input_tb值(222,'2016-01-01:10:02:00','guide');
插入input_tb值(222,'2016-01-01:10:03:00','操作');
插入input_tb值(222,'2016-01-01:10:04:00','guide');
插入input_tb值(222,'2016-01-01:10:05:00','guide');
感谢您的帮助。
苏雷什
答案 0 :(得分:0)
SELECT id, date, category,
SUM(swap) OVER (PARTITION BY id ORDER BY date)
FROM (
SELECT *,
(LAG(category) OVER (PARTITION BY id ORDER BY date) IS DISTINCT FROM category)::INTEGER swap
FROM input_tb
) q
请参阅fiddle