Postgresql Получить последние n строк для каждого client_name - PullRequest
0 голосов
/ 09 июля 2020
select timestamp, internal, external, client_name from (select *, (refno_id || ' - ' || 
client_name) ref_cl from (select distinct timestamp::text, internal::int, external::int, refnum FROM reports_jobpull_active_jobss) AS jp_active
left join
(select client_name, refno_id from accessibility_ph_refno) AS ph_refno
on jp_active.refnum = ph_refno.refno_id) jp_data where  split_part(timestamp::text,' ',1) in (SELECT distinct split_part(timestamp::text,' ',1) date FROM reports_jobpull_active_jobss order by date DESC limit 10)
order by timestamp ASC

Вышеуказанный sql запрос дает мне записи, как показано ниже.

enter image description here

For every client_name I want to get last 2 rows only. Please suggest a query to get results like that....for example, the final table will be looking like following containing only 2 last records per client_name.

введите описание изображения здесь

Ответы [ 2 ]

1 голос
/ 09 июля 2020

Пожалуйста, используйте запрос ниже. Вы можете использовать ROW_NUMBER()

select timestamp, internal, external, client_name from 
(select timestamp, internal, external, client_name, row_number() over(partition by client_name order by timestamp desc) rnk
 from (select *, (refno_id || ' - ' || 
client_name) ref_cl from (select distinct timestamp::text, internal::int, external::int, refnum FROM reports_jobpull_active_jobss) AS jp_active
left join
(select client_name, refno_id from accessibility_ph_refno) AS ph_refno
on jp_active.refnum = ph_refno.refno_id) jp_data where  split_part(timestamp::text,' ',1) in (SELECT distinct split_part(timestamp::text,' ',1) date FROM reports_jobpull_active_jobss order by date DESC limit 10)) qry
where rnk in (1,2);
1 голос
/ 09 июля 2020

Используйте row_number():

select t.*
from (select t.*, row_number() over (partition by client_name order by timestamp desc) as seqnum
      from t
     ) t
where seqnum <= 2;

Вы можете вписать это в свой запрос, используя:

with t as (
      <your query here>
     )
select t.*
from (select t.*, row_number() over (partition by client_name order by timestamp desc) as seqnum
      from t
     ) t
where seqnum <= 2;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...