2017-05-06 82 views
2
CREATED_DATE | ENTITY_ID | TYPE 
02-MAY-17 | 1234 | A 
03-MAY-17 | 1234 | B 
04-MAY-17 | 1234 | B 
05-MAY-17 | 1234 | B 

我想编写一个查询将返回:甲骨文窗函数

ENTITY_ID | DIFF_BETWEEN_A_B1 | DIFF_BETWEEN_A_B2 
1234 | 1 | 2 
... 

我想编写一个查询,将显示它获得了第一种类型的记录之间的时间和第一个TYPE B记录,以及每个ENTITY_ID的第一个TYPE A记录和第二个TYPE B记录。将有超过2个B型记录但只有一个TYPE A记录。我认为可能有一种有效的方法来使用窗口函数来做到这一点,但没有太多玩过。你会如何写这个?

+0

什么是Oracle版本? – mathguy

回答

2

这里有一个方法,使用条件汇总:

select t.entity_id, 
     max(case when seqnum = 1 and type = 'B' then created_date end) 
     - max(a_created_date) as diff_1, 
     max(case when seqnum = 2 and type = 'B' then created_date end) 
     - max(a_created_date) as diff_2 
from (select t.*, 
      min(case when type = 'A' then created_date end) over (partition by entity_id) as a_created_date, 
      row_number() over (partition by entity_id, type order by created_date) as seqnum 
     from t 
     where type in ('A', 'B') 
    ) t 
group by entity_id; 
+0

谢谢!我想你可能会在第7行结尾缺少一个逗号。 – taylordurden

+0

我得到了'不是GROUP BY表达式引起的第2行上的a_created_d。任何想法如何纠正? – taylordurden

+0

@taylordurden ..我纠正了代码..它现在应该工作。 –

1

这里是你如何能在甲骨文12.1及以上的做到这一点。

由于每个entity_id只有一行type = 'A',因此MATCH_RECOGNIZE中的排序保证我们计算所需的行将成为每个分区中的前三行。这意味着不需要DEFINE子句;但语法要求它(这就是为什么它只是要求0 = 0)。

with 
    test_data (created_date, entity_id, tp) as (
     select to_date('02-MAY-17', 'dd-MON-rr'), 1234, 'A' from dual union all 
     select to_date('03-MAY-17', 'dd-MON-rr'), 1234, 'B' from dual union all 
     select to_date('04-MAY-17', 'dd-MON-rr'), 1234, 'B' from dual union all 
     select to_date('05-MAY-17', 'dd-MON-rr'), 1234, 'B' from dual 
    ) 
-- End of test data (not part of the solution). SQL query begins below this line 
select entity_id, diff_between_a_b1, diff_between_a_b2 
from test_data 
match_recognize (
    partition by entity_id 
    order by  tp, created_date 
    measures  b1.created_date - a.created_date as diff_between_a_b1, 
       b2.created_date - a.created_date as diff_between_a_b2 
    pattern  (^ a b1 b2) 
    define  a as 0 = 0 
) 
; 

ENTITY_ID DIFF_BETWEEN_A_B1 DIFF_BETWEEN_A_B2 
--------- ----------------- ----------------- 
    1234     1     2 
+0

mathguy这是伟大的。只是一个可能的错字修复我建议 - 也许'选择entity_id,diff_between_a_b1,diff_between_a_b2'而不是'select entity_id,'谢谢 – alexgibbs

+0

@alexgibbs - 当然,谢谢。不知道这是怎么发生的 - 我以为我复制并粘贴了......显然,我没有在原来的打字错误(输出也从我的副本甲骨文复制和粘贴)。不管怎样,谢谢! – mathguy