按列分组,然后在另一列中查找更改,然后获取最后一行

时间:2015-11-18 13:28:25

标签: postgresql

我有一张这样的表:

user_name   sent_at     data
---------------------------------------------
alpha       2015-11-01  { "status" : "pending", … }
beta        2015-11-01  { "status" : "pending", …}
gamma       2015-11-01  { "status" : "pending", … }
alpha       2015-11-02  { "status" : "complete", … }
alpha       2015-11-03  { "status" : "complete", … }

对于每个用户,我想找到他达到当前状态的行。所以对于2015-11-02的用户alpha。请注意,对于同一用户,可以多次重复相同的状态。

我最终得到了:

SELECT *
FROM
(
    SELECT 
        user_name,
        sent_at,
        status,
        row_number() OVER (PARTITION BY user_name ORDER BY sent_at DESC) as row
    FROM
    (
        SELECT
            user_name,
            sent_at,
            data->>'status' AS status,
            lag(data->>'status') OVER (PARTITION BY user_name ORDER BY sent_at) AS prev_status
        FROM log
    ) AS t
    WHERE status IS DISTINCT FROM prev_status
) AS u 
WHERE row = 1

有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

您的查询看起来不错imho。如果您想避免使用窗口函数,可以使用$ mvn -Dexec.mainClass=... -Dexec.classpathScope=test clean exec:java 两次distinct on向相反方向排序:

sent_at