簡體   English   中英

Oracle 分析函數?

[英]Oracle Analytical Function?

對於下表,我們如何找到名字連續出現 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;

我相信我們可以通過使用領先/滯后來獲取上一行和下一行來做到這一點。 雖然我的解決方案提供了所需的輸出,但我認為這不是正確的解決方案。

你的方法很接近。 你還需要一個比較:

select distinct cust_name 
from (select c.*
             lag(cust_name) over (order by cust_id)  as prev_cust_name,
             lead(cust_name) over (order by cust_id) as next_cust_name
      from customer c
     ) a c
where prev_cust_name = cust_name and cust_name = next_cust_name;

對於更通用的解決方案,您可以比較兩個滯后:

select distinct cust_name 
from (select c.*
             lag(cust_id, 2) over (order by cust_id)  as prev2_cust_id,
             lag(cust_id, 2) over (partitioin by name order by cust_id)  as prev2_cust_id_name
      from customer c
     ) a c
where prev2_cust_id = prev2_cust_id_name;

這看起來是兩行——一次僅通過cust_id和一次僅用於名稱。 如果cust_id值相同,則所有行都具有相同的名稱。 您可以將2調整為任何值。

如果要查找N個連續值,可以使用窗口函數。 請參見 N = 4 的示例:

with params (n) as (select 4 from dual) -- Set N = 4
select distinct cust_name
from (
  select
    cust_id, cust_name, n,
    min(cust_name) over 
      (order by cust_id rows between n - 1 preceding and current row) as mi,
    max(cust_name) over
      (order by cust_id rows between n - 1 preceding and current row) as ma,
    count(*) over
      (order by cust_id rows between n - 1 preceding and current row) as cnt
  from customer
  cross join params
) x
where mi = ma and cnt = n

請參閱SQL Fiddle 中的運行示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM