选择sql中的列值和下一个最高的列值

6kkfgxo0  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(363)

我有两列:userid和date。我想要第三列,对于每一行(每个userid和date\u accessed组合),它返回date\u accessed的下一个最高日期。现在我的问题是:

SELECT 
   userid, 
   date_accessed AS first_date,
   (SELECT date_accessed
    FROM table
    WHERE date_accessed > first_date
    ORDER BY date_accessed ASC
    LIMIT 1) AS second_date
FROM table

但这不起作用-有人能帮我理解为什么吗?

smdncfj3

smdncfj31#

使用子查询,正确的语法是:

SELECT t.userid, t.date_accessed AS first_date,
       (SELECT t2.date_accessed
        FROM table t
        WHERE t2.date_accessed > t.date_accessed
        ORDER BY t2.date_accessed ASC
        LIMIT 1
       ) AS second_date
FROM table t;

注意,列引用都是用它们的表名限定的。
如果希望每个用户都这样,还需要一个相关子句:

SELECT t.userid, t.date_accessed AS first_date,
       (SELECT t2.date_accessed
        FROM table t
        WHERE t2.userid = t.userid AND t2.date_accessed > t.date_accessed
        ORDER BY t2.date_accessed ASC
        LIMIT 1
       ) AS second_date
FROM table t;

如果日期是唯一的,您可以使用 LEAD() :

select t.*,
       lead(date_accessed) over (partition by userid order by date_accessed)
from t;

相关问题