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

4ioopgfo  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(171)

我试图构造一个查询,只检索每个客户的最新状态更新。
我已经附上了一个图像的数据是如何目前建设和我希望它如何返回。

omjgkv6w

omjgkv6w1#

您没有指定正在使用的数据库。如果它实现元组相等,则可以执行以下操作:

select *
from t
where (customer, status_time) in (
  select customer, max(status_time) from t group by customer
)

在postgresql中,您可以使用 DISTINCT ON . 在最坏的情况下,您需要使用一个相关的子查询;它比较慢,但可以做这项工作。
为sql server编辑
在sql server中,可以使用cte预计算最大状态时间。例如,您可以执行以下操作:

with
a as (
  select customer, max(status_time) as max_time
  from t 
  group by customer
)
select
from t
join a on a.customer = t.customer 
      and a.max_time = t.status_time

相关问题