从有序结果集中查找“行"行 [英] Finding a 'run' of rows from an ordered result set

查看:47
本文介绍了从有序结果集中查找“行"行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出一种识别满足一定条件的结果(连续的行)的方式".目前,我正在订购结果集,并通过肉眼扫描特定模式.这是一个示例:

I'm trying to figure out a way of identifying a "run" of results (successive rows, in order) that meet some condition. Currently, I'm ordering a result set, and scanning by eye for particular patterns. Here's an example:

SELECT the_date, name
FROM orders
WHERE 
    the_date BETWEEN 
        to_date('2013-09-18',..) AND 
        to_date('2013-09-22', ..)
ORDER BY the_date

--------------------------------------
the_date            | name
--------------------------------------
2013-09-18 00:00:01 | John
--------------------------------------
2013-09-19 00:00:01 | James
--------------------------------------
2013-09-20 00:00:01 | John
--------------------------------------
2013-09-20 00:00:02 | John
--------------------------------------
2013-09-20 00:00:03 | John
--------------------------------------
2013-09-20 00:00:04 | John
--------------------------------------
2013-09-21 16:00:01 | Jennifer
--------------------------------------

我要从此结果集中提取的是归因于2013-09-20John的所有行.通常,我要寻找的是连续来自同一name的结果,其结果是==3.我使用的是Oracle 11,但我想知道是否可以使用严格的SQL来实现,或是否必须使用某种分析功能.

What I want to extract from this result set is all the rows attributed to John on 2013-09-20. Generally what I'm looking for is a run of results from the same name, in a row, >= 3. I'm using Oracle 11, but I'm interested to know if this can be achieved with strict SQL, or if some kind of analytical function must be used.

推荐答案

您需要多个嵌套窗口函数:

You need multiple nested window functions:

SELECT *
FROM
 (
   SELECT the_date, name, grp,
      COUNT(*) OVER (PARTITION BY grp) AS cnt
   FROM
    (
      SELECT the_date, name, 
         SUM(flag) OVER (ORDER BY the_date) AS grp
      FROM
       (
         SELECT the_date, name, 
            CASE WHEN LAG(name) OVER (ORDER BY the_date) = name THEN 0 ELSE 1 END AS flag
         FROM orders
         WHERE 
             the_date BETWEEN 
                 TO_DATE('2013-09-18',..) AND 
                 TO_DATE('2013-09-22', ..)
       ) dt
    ) dt
 ) dt
WHERE cnt >= 3
ORDER BY the_date

这篇关于从有序结果集中查找“行"行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆