返回整行的多个元素的最大值

时间:2019-03-29 18:24:50

标签: sql

我有一个看起来像这样的表:

id_this_table   fk_tableX    fk_tableY    ts_started    ts_activated     ts_expired
      1             1            1        2019-03-20     2019-03-21      2019-03-22
      2             1            2        2019-03-23     2019-03-24      2019-03-25
      3             2            3        2019-03-23     2019-03-24      2019-03-26

对于多个元素,我需要通过fk_tableX获取每个元素的最新信息。就像订阅一样,我需要获取每个“客户端”中最新的一个

结果应该像这样

  id_this_table   fk_tableX    fk_tableY  ts_started    ts_activated     ts_expired
      2             1            2        2019-03-23     2019-03-24      2019-03-25
      3             2            3        2019-03-23     2019-03-24      2019-03-26

1 个答案:

答案 0 :(得分:1)

使用相关子查询

select t1.* from table_name t1
where t1.ts_expired=( select max(ts_expired) from table_name t2 where t1.fk_tableX=t2.fk_tableX)

或在您的dbms支持的情况下使用row_number()

with cte as
(select t.*,row_number() over(partition by fk_tableX order by ts_expired desc) rn from table_name t
) select * from cte where rn=1
相关问题