SQL 统计连续出现的次数

问题:一个表记录了某论坛会员的发贴情况,存储了会员uid ,发贴时间post_time和内容content。找出连续发贴三次及以上的会员。

upload successful

1
2
3
4
5
6
7
8
9
select b.uid from
(select a.uid uid,a.row2-a.row1,count(uid) from
(select uid,post_time,
row_number() over (partition by uid order by post_time) as row1,
row_number() over (order by post_time) as row2
from tablename) a
group by a.uid,a.row2-a.row1
having count(uid)>=3) b
group by b.uid

过程理解:按post_time排序后,只有连续出现的uid行row2-row1才相等,否则就是不等,因此count(pid) group by uid,row2-row1中,count(pid)表示uid连续出现的次数,3次就count(pid)=3,n次就count(pid)=n

upload successful

upload successful
转:
https://blog.csdn.net/zhenglit/article/details/88063821