使用 row_partition 内的过滤器进行过滤和排名(使用 row_partition)

Filter and rank (using row_partition) with a filter inside the row_partition

我有一个 table Jobs 存储来自 *Users post 的每个用户的一堆作业秒。每个作业都有一个状态。我的第一个目标是为每个用户确定第一个完成的(状态 = 已完成)作业。我能够使用:

SELECT
    user_id AS user_id,
    starts_time AS starts_time,
    id AS job_id
FROM (
    SELECT
        user_id,
        starts_time,
        id,
        --sort by starts time, and rank ascending
        Row_number() OVER (PARTITION BY User_id ORDER BY Starts_time ASC) AS Rn
    FROM
        jobs
    WHERE
        --status 2 is completed
        status = 2
    GROUP BY
        user_id,
        assignment_id,
        id ORDER BY
            user_id) AS jobs
WHERE
    rn = 1

这是 returns:

user_id   | starts_time             |  job_id |
-----------------------------------------------
 123      | 2016-04-18 14:30:00+00  |   1292  |
 124      | 2016-04-18 19:00:00+00  |   2389  |
 128      | 2016-04-16 13:00:00+00  |   3201  |

正如某些情况,在很多情况下,用户的第一份工作并不是状态为“已完成”的工作。例如,他们会 post 一份工作列表,在他们看到完成的工作之前,这些工作具有以下任何一种状态:(“未填写”、“作废”、“已取消”)

对于每个用户,我想确定在该用户看到他们的第一个完成的工作之前有哪些工作。我希望上面的查询将是一个起点,从那以后我可以说 return 我为每个用户提供的任何工作,之前有 starts_time 第一份工作完成

*抱歉,如果这令人困惑,这是我第一次 post 在 Stack Overflow 上寻求帮助,欢迎任何建设性的批评!

For every user I want to establish which jobs came before that user saw their first completed job.

对于每个用户,您希望所有记录的第一个状态为“2”。您可以使用 window 函数:

select *
from (
    select j.*,
        bool_or(status = 2) over(partition by user_id order by starts_time) as flag
    from jobs j
) t
where not flag 

bool_or 检查当前行或任何前面的行是否满足条件。

如果想保留第一个状态2,那么只要将window函数的over()子句改成不考虑当前行即可:

select *
from (
    select j.*,
        bool_or(status = 2) over(
            partition by user_id 
            order by starts_time rows between unbounded preceding and 1 preceding
        ) as flag
    from jobs j
) t
where flag is distinct from true