Oracle递归查询(比较分组数据中的时间戳)

时间:2016-05-02 22:26:51

标签: oracle recursion subquery

我有数据,其中有几个人可以属于同一个帐户ID,原始成员是主要成员。我正在尝试编写一个查询,对于每个拥有一个或多个成员的帐户ID,返回任何时间戳大于主要帐户的非主要帐户。

所以使用样本数据:

ID  account ID  Timestamp   Primary
1   111        4/26/2011 0:00   1
2   112        4/26/2011 0:00   1
3   112        4/27/2011 0:00   0
4   113        4/26/2011 0:00   1
5   113        4/29/2011 0:00   0
6   113        4/28/2011 0:00   0
7   114        4/26/2011 0:00   1
8   114        4/26/2011 0:00   0

我想返回以下内容

ID  account ID  Timestamp   Primary
3   112         4/27/2011 0:00  0
5   113         4/29/2011 0:00  0
6   113         4/28/2011 0:00  0

所以流程如下:

  1. 使用>查找所有帐户ID 1条记录
  2. 对于每个帐户ID,返回所有非主要记录(即primary = 0),其中时间戳大于该帐户ID的主要记录。
  3. 简而言之,我试图找到以后添加到帐户中的所有成员。

    我一直在查看子查询和分层查询,但绝对可以使用一些帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

Oracle安装程序

CREATE TABLE table_name ( ID, account_ID, "Timestamp", "Primary" ) AS
SELECT 1, 111, TIMESTAMP '2011-04-26 00:00:00', 1 FROM DUAL UNION ALL
SELECT 2, 112, TIMESTAMP '2011-04-26 00:00:00', 1 FROM DUAL UNION ALL
SELECT 3, 112, TIMESTAMP '2011-04-27 00:00:00', 0 FROM DUAL UNION ALL
SELECT 4, 113, TIMESTAMP '2011-04-26 00:00:00', 1 FROM DUAL UNION ALL
SELECT 5, 113, TIMESTAMP '2011-04-29 00:00:00', 0 FROM DUAL UNION ALL
SELECT 6, 113, TIMESTAMP '2011-04-28 00:00:00', 0 FROM DUAL UNION ALL
SELECT 7, 114, TIMESTAMP '2011-04-26 00:00:00', 1 FROM DUAL UNION ALL
SELECT 8, 114, TIMESTAMP '2011-04-26 00:00:00', 0 FROM DUAL;

<强>查询

SELECT *
FROM   (
  SELECT t.*,
         LAG( CASE "Primary" WHEN 1 THEN 1 END ) IGNORE NULLS
           OVER ( PARTITION BY account_id ORDER BY "Timestamp", "Primary" )
           AS has_prev_primary
  FROM   table_name t
)
WHERE  has_prev_primary = 1;

<强>输出

        ID ACCOUNT_ID Timestamp                       Primary HAS_PREV_PRIMARY
---------- ---------- ----------------------------- --------- ----------------
         3        112 2011-04-27 00:00:00.000000000         0                1 
         6        113 2011-04-28 00:00:00.000000000         0                1 
         5        113 2011-04-29 00:00:00.000000000         0                1