在购买之前获取最后一个事件

时间:2018-06-26 01:46:51

标签: sql-server

有人可以帮助我进行查询,以获得购买之前的最新记录。 数据集如下所示

UserID  EventType   ProductID   EventTime   Price   Campaign
123ABC  Click   P1  5/9/2018 2:33   NULL    C1
123ABC  Click   P1  5/10/2018 2:07  NULL    C1
123ABC  Click   P1  5/16/2018 2:14  NULL    C1
123ABC  Click   P2  5/9/2018 2:33   NULL    C1
123ABC  Click   P2  5/10/2018 2:07  NULL    C1
123ABC  Click   P2  5/16/2018 2:14  NULL    C1
123ABC  Purchase    P2  5/22/2018 4:11  19.44   NULL
123ABC  Click   P3  5/9/2018 2:33   NULL    C1
123ABC  Click   P3  5/10/2018 2:07  NULL    C1
123ABC  Click   P3  5/11/2018 15:57 NULL    C1
123ABC  Click   P3  5/16/2018 2:14  NULL    C1
123ABC  Purchase    P4  5/22/2018 4:11  31.44   NULL

输出

UserID  EventType   ProductID   EventTime       Price   Campaign
123ABC  Click        P2         5/16/2018 2:14  19.44   C1
123ABC  NoEvent      P4         5/22/2018 4:11  31.44   NULL

我需要在购买前点击发生时找到最后一条记录 即

  123ABC  Click   P2  5/16/2018 2:14  NULL    C1

如果在购买特定产品之前没有点击,那么只需输出购买记录

123ABC  NoEvent      P4         5/22/2018 4:11  31.44   NULL

我尝试使用以下查询找到导致购买的记录组的顺序  例子

Select *, row_number() over(partition by UserId,ProductId order by EventTime) as Ordering from Purchase

UserID  EventType   ProductID   EventTime   Price   Campaign Ordering
123ABC  Click   P1  5/9/2018 2:33   NULL    C1 1
123ABC  Click   P1  5/10/2018 2:07  NULL    C1 2
123ABC  Click   P1  5/16/2018 2:14  NULL    C1 3 
123ABC  Click   P2  5/9/2018 2:33   NULL    C1 1
123ABC  Click   P2  5/10/2018 2:07  NULL    C1 2
123ABC  Click   P2  5/16/2018 2:14  NULL    C1 3
123ABC  Purchase    P2  5/22/2018 4:11  19.44   NULL 4
123ABC  Click   P3  5/9/2018 2:33   NULL    C1 1
123ABC  Click   P3  5/10/2018 2:07  NULL    C1 2
123ABC  Click   P3  5/11/2018 15:57 NULL    C1 3
123ABC  Click   P3  5/16/2018 2:14  NULL    C1 4
123ABC  Purchase    P4  5/22/2018 4:11  31.44   NULL 5

通过上面的分组,我只需要考虑其中已购买的那些组,然后过滤数据。目前,我坚持使用这种方法。 有人可以帮我解决这个问题吗

SQLFiddle

2 个答案:

答案 0 :(得分:1)

create table temp (
  EventType varchar(10),
  ProductID varchar(10),
  Ordering int,
  Price int
);

insert into temp
Select EventType, ProductID,
row_number(), Price
over(partition by UserId,ProductId order by EventTime) as Ordering 
from Purchase;


select p.UserID, p.EventType, p.ProductID, p.EventTime, t.Price, p.Campaign from (
select ProductID, CASE WHEN Ordering = 1 THEN 1 ELSE Ordering -1 END as Ordering, Price
from temp t
where t.EventType = 'Purchase') a,
(
Select *,
row_number() 
over(partition by UserId,ProductId order by EventTime) as Ordering 
from Purchase
) p
where a.ProductID = p.ProductID
and a.Ordering = p.Ordering

可以肯定,可以改进它以减少某些语法...我认为不必创建新的临时表。此外,您想要这个结果吗?

答案 1 :(得分:1)

Address of num: 0xffffcba6
Enter the address: 0xffffcba6

address = 0xffffcba6
The value at address 0xffffcba6 = 0
Process returned 0 (0x0)   execution time : 2.719 s
Press any key to continue.

这还将满足同一用户多次购买同一产品的情况。我添加了一些示例数据来测试查询。检查并让我知道它们是否无效。 SQL Fiddle