对于下表,我们如何找到名称连续出现 3 次的客户。
+---------+-----------+
| CUST_ID | CUST_NAME |
+---------+-----------+
| 1 | SAM |
+---------+-----------+
| 2 | SAM |
+---------+-----------+
| 3 | SAM |
+---------+-----------+
| 4 | PETER |
+---------+-----------+
| 5 | PETER |
+---------+-----------+
Desired_Output
+-----------+
| CUST_NAME |
+-----------+
| SAM |
+-----------+
表定义:
create table Customer
(
cust_id int,
cust_name varchar2(20)
);
insert into customer values (1, 'SAM');
insert into customer values (2, 'SAM');
insert into customer values (3, 'SAM');
insert into customer values (4, 'PETER');
insert into customer values (5, 'PETER');
到目前为止尝试过的代码
Select distinct cust_name from (
select
cust_id,
cust_name,
lag(cust_name,1,0) over (order by cust_id) as prev_cust_name,
lead(cust_name,1,0) over (order by cust_id) as next_cust_name
from customer) a
where a.prev_cust_name=a.next_cust_name;
我相信我们可以通过使用领先/滞后来获得上一行和下一行来做到这一点。尽管我的解决方案提供了所需的输出,但我认为这不是正确的解决方案。