我有一个存储过程,返回三列
| ID | EVENTS_ID | EVENT_TIME_FROM |
| 46 | 1 | "2015-03-09 15:00:00" |
| 46 | 2 | "2015-03-16 15:00:00" |
| 46 | 3 | "2015-03-18 15:00:00" |
| 47 | 4 | "2015-03-12 16:30:00" |
| 47 | 5 | "2015-03-23 16:30:00" |
| 47 | 6 | "2015-03-23 16:30:00" |
| 47 | 7 | "2015-03-23 16:30:00" |
| 47 | 8 | "2015-03-23 16:30:00" |
我想查询每个ID最大EVENT_TIME_FROM的所有id + events_ids
即。结果将是
| ID | EVENTS_ID | EVENT_TIME_FROM |
| 46 | 3 | "2015-03-18 15:00:00" |
| 47 | 5 | "2015-03-23 16:30:00" |
| 47 | 6 | "2015-03-23 16:30:00" |
| 47 | 7 | "2015-03-23 16:30:00" |
| 47 | 8 | "2015-03-23 16:30:00" |
另外,为了使这个更加困难,表格实际上是存储过程调用的结果,而且已经是一些组。
即。当前查询是
SELECT DISTINCT id,events_id, event_time_from
FROM my_stored_proc(...data)
GROPU BY id, events_id, event_time_from
ORDER BY id ,events_id ,event_time_from DESC
我在Postgres,尝试了一些但不确定的事情。
答案 0 :(得分:2)
如何使用rank()
等排名功能:
select id,events_id, event_time_from,
from (
select id,events_id, event_time_from,
rank() over (partition by id order by event_time_from desc) rnk
from my_stored_proc(...data)
) t
where rnk = 1
或者,您可以使用max()
聚合:
select m.id,m.events_id,m.event_time_from
from my_stored_proc(...data) m
join (
select id, max(event_time_from) event_time_from
from my_stored_proc(...data)
group by id
) t on m.id = t.id and m.event_time_from = t.event_time_from