如何使用每个客户的最新状态更新提取数据



我正在尝试构造一个查询,该查询只会检索每个客户的最新状态更新。 我附上了当前如何构建数据以及我希望如何返回数据的图像。 在此处输入图像描述

给定表名是customer_requests,最简单的解决方案是:

select
cr1.*
from
customer_requests cr1
inner join customer_requests cr2 on
cr1.customer = cr2.customer
group by
cr1.customer,
cr1.status,
cr1.status_time_stamp
having
cr1.status_time_stamp = max(cr2.status_time_stamp);

上面的解决方案是使用customer进行自我加入,但它的效率不高。

更有效的解决方案是:

select
cr1.*
from
customer_requests cr1
inner join (
select
cr2.customer, max(cr2.status_time_stamp) as most_recent_timestamp
from
customer_requests cr2
group by
cr2.customer) vcr on
cr1.customer = vcr.customer
and cr1.status_time_stamp = vcr.most_recent_timestamp;

现在,自联接是使用别名vcr(表示 customer_requests 的虚拟表(的内联表完成的,内联表大大减少了要进行的连接数量,从而提高了查询的性能。

如果您使用 SQL Server:

select distinct customerID,t2.status,t2.date
from table  t
cross apply 
(select top 1 status ,date        
from customer 
where customerID=t.customerID   
order by date desc) t2

最新更新