SQL,给连续的行加上标识序号

postgresql 数据库的表 tmp 有 2 个分组字段,source_id 和 event_user,将该表按 source_id 分组,组内按 event_date 排序后,event_user 相同的值会形成有序的小组:

id source_id event_user event_date
1 1 A 05-03-2014
2 1 A 06-03-2014
3 1 B 07-03-2014
4 1 B 08-03-2014
5 1 A 09-03-2014
6 1 A 10-03-2014
7 1 A 11-03-2014
8 2 A 12-03-2014
9 2 B 13-03-2014
10 2 A 14-03-2014
11 2 B 15-03-2014
12 2 B 16-03-2014
现在要增加计算列SERIES_ID,在source_id内按顺序给每个有序小组加序号。
id source_id SERIES_ID event_user event_date
1 1 1 A 05-03-2014
2 1 1 A 06-03-2014
3 1 2 B 07-03-2014
4 1 2 B 08-03-2014
5 1 3 A 09-03-2014
6 1 3 A 10-03-2014
7 1 3 A 11-03-2014
8 2 1 A 12-03-2014
9 2 2 B 13-03-2014
10 2 3 A 14-03-2014
11 2 4 B 15-03-2014
12 2 4 B 16-03-2014

编写SPL代码:

A
1 =post1.query("select id, source_id, SERIES_ID, event_user, event_date from data order by source_id,event_date")
2 =A1.group@o(source_id).(~.group@o(event_user))
3 =A2.conj@r(~.run( ~.run( SERIES_ID=get(1,#))))

A1:SQL取数,按source_id,event_date排序,其中SERIES_ID 为空。

A2:不排序,按source_id相邻的值分组,组内按 event_user 相邻的值再分小组。

A3:在大组内给每个小组赋予序号,合并各组到记录级。

开源SPL源码地址

免费下载

猜你喜欢

转载自blog.csdn.net/smilejingwei/article/details/142916501