我有一个交易表,我必须在其中找到每个客户的第一个和第二个交易日期。查找第一个日期非常简单,我可以使用 MIN() func 来查找第一个日期,但是第二个日期,特别是找到两者之间的差异变得非常具有挑战性,不知何故我无法找到任何可行的方法:
select a.customer_id, a.transaction_date, a.Row_Count2
from ( select
transaction_date as transaction_date,
reference_no as customer_id,
row_number() over (partition by reference_no
ORDER BY reference_no, transaction_date) AS Row_Count2
from transaction_detail
) a
where a.Row_Count2 < 3
ORDER BY a.customer_id, a.transaction_date, a.Row_Count2
给我这个:
我想要的是,以下列:
||客户ID|| ||第一次购买日期|| ||购买的第二个日期|| ||差异。黑白第二次和第一次约会 ||
您可以使用窗口函数 LEAD/LAG 返回您要查找的结果
首先尝试使用 LEAD 通过参考号查找所有前导日期,使用原始逻辑为每一行生成行号。然后,您可以对结果集中的行编号值 1 行的日期进行差异处理。
例如(我不排除同一天的交易并将它们视为单独的并根据上面查询的结果集生成行号,您可以轻松地更改下面的 sql 将它们视为一个并删除它们,以便您获得下一个日期第二次约会):
declare @tbl table(reference_no int, transaction_date datetime)
insert into @tbl
select 1000, '2018-07-11'
UNION ALL
select 1001, '2018-07-12'
UNION ALL
select 1001, '2018-07-12'
UNIOn ALL
select 1001, '2018-07-13'
UNIOn ALL
select 1002, '2018-07-11'
UNIOn ALL
select 1002, '2018-07-15'
select customer_id, transaction_date as firstdate,
transaction_date_next seconddate,
datediff(day, transaction_date, transaction_date_next) diff_in_days
from
(
select reference_no as customer_id, transaction_date,
lead(transaction_date) over (partition by reference_no
order by transaction_date) transaction_date_next,
row_number() over (partition by reference_no ORDER BY transaction_date) AS Row_Count
from @tbl
) src
where Row_Count = 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句