我有数据,其中有几个人可以属于同一个帐户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
所以流程如下:
简而言之,我试图找到以后添加到帐户中的所有成员。
我一直在查看子查询和分层查询,但绝对可以使用一些帮助。谢谢!
答案 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