0

我有一个记录的“状态更改”表。我需要找到用户的最新状态更改,如果是 a) 某种“类型”的状态更改 ( s.new_status_id),并且 b) 超过 7 天 ( s.change_date),则将其包含在结果中。我当前的查询有时会返回给定用户的倒数第二个状态更改,这是我不想要的——我只想评估最后一个。

如何修改此查询,使其仅包含该用户最近的状态更改的记录?

询问

SELECT DISTINCT ON (s.applicant_id) s.applicant_id, a.full_name, a.email_address, u.first_name, s.new_status_id, s.change_date, a.applied_class
        FROM automated_responses_statuschangelogs s
        INNER JOIN application_app a on (a.id = s.applicant_id)
        INNER JOIN accounts_siuser u on (s.person_who_modified_id = u.id)
        WHERE now() - s.change_date > interval '7' day
        AND s.new_status_id IN
            (SELECT current_status
             FROM application_status
             WHERE status_phase_id = 'In The Flow'
            )
        ORDER BY s.applicant_id, s.change_date DESC, s.new_status_id, s.person_who_modified_id;
4

1 回答 1

1

您可以使用row_number()筛选每个申请人的条目:

select  *
from    (
        select  row_number() over (partition by applicant_id 
                                   order by change_date desc) rn
        ,       *
        from    automated_responses_statuschangelogs
        ) as lc
join    application_app a 
on      a.id = lc.applicant_id
join    accounts_siuser u 
on      lc.person_who_modified_id = u.id
join    application_status stat
on      lc.new_status_id = stat.current_status
where   lc.rn = 1
        and stat.status_phase_id = 'In The Flow'
        and lc.change_date < now() - interval '7' day
于 2013-09-04T05:55:36.263 回答