我遇到了这个问题:
给定包含user_id,时间戳和收入的收入交易表,您如何找到每个用户的第三次购买?
我知道如何使用窗口函数来解决它,但我不知道如何在没有窗口函数的情况下解决它.例如,相关子查询.
如果我们想要n购买,您的方法是否有效?
在MySQL中,我会使用变量:
select t.*
from (select t.*,
(@rn := if(@u = user_id, @rn + 1,
if(@u := user_id, 1, 1)
)
) as rn
from (select t.*
from transactions t
order by user_id, timestamp
) t cross join
(select @rn := 0, @u := -1) params
) t
where rn = 3;
Run Code Online (Sandbox Code Playgroud)
也就是说,老式的SQL方法是一个相关的子查询:
select t.*
from transactions t
where 3 = (select count(*)
from transactions t2
where t2.user_id = t.user_id and t2.timestamp <= t.timestamp
);
Run Code Online (Sandbox Code Playgroud)