我有一个交易表,我必须在这里找到每个客户的交易的第一天和第二天。在我可以使用MIN()函数来查找第一个日期的情况下,查找第一个日期非常简单,但是第二个日期(尤其是查找两者之间的差异)变得非常具有挑战性,并且我无法以某种方式找到可行的方法:>
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 || || FirstDateofPurchase || ||第二个购买日期|| || Diff。黑白第二次和第一次约会||
答案 0 :(得分:0)
您可以使用窗口功能LEAD / LAG返回所需的结果
首先尝试使用LEAD通过参考编号查找所有前导日期,然后使用原始逻辑为每一行生成行编号。然后,您可以对结果集中第1行的行号的日期进行差异。
Ex(我不排除当日交易并将其视为单独的交易,并根据上面查询的结果集生成行号,您可以轻松地更改以下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
答案 1 :(得分:0)
您可以使用CROSS APPLY
进行此操作。
SELECT td.customer_id, MIN(ca.transaction_date), MAX(ca.transaction_date),
DATEDIFF(day, MIN(ca.transaction_date), MAX(ca.transaction_date))
FROM transaction_detail td
CROSS APPLY (SELECT TOP 2 *
FROM transaction_detail
WHERE customer_id = td.customer_id
ORDER BY transaction_date) ca
GROUP BY td.customer_id