Oracle SQL—两个失败事件之间的案例数(G图表)

Oracle SQL—两个失败事件之间的案例数(G图表),sql,oracle,oracle11g,Sql,Oracle,Oracle11g,以下是我目前正在处理的数据示例: 101 N 4/14/2016 201 Y 4/15/2016 301 Y 4/16/2016 401 Y 4/20/2016 501 N 4/21/2016 201 Y 4/30/2016 701 Y 5/03/2016 301 N 5/03/2016 期望输出: 101 N 4/14/2016 0 501 N 4/21/2016

以下是我目前正在处理的数据示例:

101     N   4/14/2016
201     Y   4/15/2016
301     Y   4/16/2016
401     Y   4/20/2016
501     N   4/21/2016
201     Y   4/30/2016
701     Y   5/03/2016
301     N   5/03/2016
期望输出:

101    N    4/14/2016    0
501    N    4/21/2016    3
301    N    5/03/2016    2 
我需要两个失败事件之间成功案例的计数来绘制G图表。
我真的需要一些帮助来找到一种计算成功案例的方法。

您可以使用之前的“N”事件计数来枚举组。然后,您的查询只是一个聚合查询:

select min(col1) as col1, min('N') as col2, min(date) as col3,
       sum(case when col2 = 'Y' then 1 else 0 end) as cnt
from (select t.*,
             sum(case when col2 = 'N' then 1 else 0 end) over (order by col3) as grp
      from t
     ) t
group by grp;
假设DT列(第三列)没有重复的值-我更改了最后一个日期以反映这一点,在我的测试数据中-这可以通过在内部查询中计算“Y”行(在分析计数中使用CASE表达式)来解决,然后在外部查询中,我们可以仅过滤带有“N”的行并使用滞后差(还是一个分析函数应用程序)

如果DT列中可能存在联系,那么OP需要澄清需求——但不管是什么,它都可以很容易地适应此解决方案

with
     test_data ( id, success, dt ) as (
       select 101, 'N', to_date('4/14/2016', 'mm/dd/yyyy') from dual union all
       select 201, 'Y', to_date('4/15/2016', 'mm/dd/yyyy') from dual union all
       select 301, 'Y', to_date('4/16/2016', 'mm/dd/yyyy') from dual union all
       select 401, 'Y', to_date('4/20/2016', 'mm/dd/yyyy') from dual union all
       select 501, 'N', to_date('4/21/2016', 'mm/dd/yyyy') from dual union all
       select 201, 'Y', to_date('4/30/2016', 'mm/dd/yyyy') from dual union all
       select 701, 'Y', to_date('5/03/2016', 'mm/dd/yyyy') from dual union all
       select 301, 'N', to_date('5/04/2016', 'mm/dd/yyyy') from dual
     )
--  End of simulated data (for testing purposes only).
--  Solution (SQL query) begins BELOW THIS LINE.
select id, success, dt, ct - lag(ct, 1, 0) over (order by dt) as success_count
from   (
         select id, success, dt,
                count(case when success = 'Y' then 1 end) over (order by dt) as ct
         from   test_data
       )
where  success = 'N'
;

 ID SUCCESS DT         SUCCESS_COUNT
--- ------- ---------- -------------
101 N       14/04/2016             0
501 N       21/04/2016             3
301 N       04/05/2016             2

请阅读:我们如何知道301行在701行之后,而不是之前?它们的日期相同!它们只是一个随机数。我只是想澄清col1不是主键。你的意思是它不是“唯一的”?(我假设它是“非空的”)。如果它不是唯一的,你如何决定应该考虑Y还是N“第一个”(在另一个之前)?分钟(日期)将产生一个问题。最后,我只需要日期和案件数量。101 Y 4/1/2016 102 Y 4/1/2016 103 N 4/2/2016 104 Y 4/2/2016 105 N 4/3/2016运行您的查询将给出以下输出:N 4/1/2016 2 N 4/2/2016 1 N 4/3/2016 0我们还有一列是datetime格式的。它被相应地排序了。但这就是我想弄明白的。它对我有用。谢谢@mathguy.:)@SJA-这是分析函数的魅力之一-分析子句(OVER子句中的partitionby和ORDER BY)具有很大的灵活性,您可以按需要的任何表达式或表达式组合进行排序。