相对新手在这里..我正在尝试编写一个查询,其中有一个事务列表,我需要查看60天后是否发生了不同的事务类型
E.g. A
Trans 1 : 1/1/18
Trans 2 : 1/11/17, 1/12/17, 2/1/18, 1/2/18, 1/3/18, 17/3/18
Did a trans 2 occurs within 60 days post trans 1 : Y
--> I don't want to return this example
...
E.g. B
Trans 1 : 1/1/18
Trans 2 : 1/11/17, 1/12/17, 31/12/17, 17/3/18, 21/3/18
Did a trans 2 occurs within 60 days post trans 1 : N
--> I want to return this example
...
SELECT * FROM
(SELECT e.ID, sa.id ** LIST OF TRANSACTIONS #1*
FROM table1 e,
table3 sa
WHERE e.type_id = 'ABC'
AND sa.type_id = 'PRE'
) S1,
(SELECT sa.id, adj.date AS vdate ** LIST OF TRANSACTIONS #2**
FROM table4 sa,
table5 adj
WHERE sa.id = adj.id
) S2
WHERE S1.id = S2.id
and s2.vdate > S1.E_DT
** ME TRYING TO COMPARE IF 1 date of TRANS 2 is after 60 days of TRANS 1**
and s2.vdate < S1.E_DT + 60
and s2.vdate not between (S1.E_DT) and (S1.E_DT + 60 )
Trans类型2将在trans类型1的过去和将来具有大范围的日期。
从我的谷歌搜索,我认为我需要一个案例选项或可能不存在?
你能指出我正确的方向吗?
由于 萨拉
答案 0 :(得分:0)
如果您想要在60天内没有交易#2的交易#1列表,我会使用NOT EXISTS:
select *
from
(... your subquery ...) s1
where not exists
(select 1 from
(...) s2
where s1.id = s2.id
and s2.vdate between s1.e_dt and s1.e_dt + 60);
如果你想看看所有的交易#1并看到一个标志,显示他们是否在60天内跟随了#2交易,我将NOT EXISTS移到SELECT子句中使用CASE。
select s1.*,
CASE WHEN not exists
(select 1 from
(...) s2
where s1.id = s2.id
and s2.vdate between s1.e_dt and s1.e_dt + 60)
THEN 'Y' ELSE 'N' END as no_trans2_in_60_days
from
(...) s1
;
您也可以将此作为外部联接,但就您的示例而言,我认为这不值得麻烦。