在给定日期之前找到“状态更改”的正确SQL查询是什么?

时间:2013-09-04 05:48:12

标签: sql postgresql

我有一张记录'状态变化'的表格。我需要找到用户的最新状态更改,如果是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;

1 个答案:

答案 0 :(得分: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