how to do lag operation in mysql

前端 未结 1 358
不知归路
不知归路 2020-12-16 06:40

Guys I want to use analytical function lag in mysql. In Oracle it is supported but I can\'t do it in Mysql. So can anybody help me how to perform lag operation in Mysql? For

相关标签:
1条回答
  • 2020-12-16 07:09

    You can emulate it with user variables:

    select uid, operation, previous_operation from (
    select
    y.*
    , @prev AS previous_Operation
    , @prev := Operation
    from
    your_table y
    , (select @prev:=NULL) vars
    order by uid
    ) subquery_alias
    
    • see it working in an sqlfiddle live

    Here you initialize your variable(s). It's the same as writing SET @prev:=NULL; before writing your query.

    , (select @prev:=NULL) vars
    

    Then the order of these statements in the select clause is important:

    , @prev AS previous_Operation
    , @prev := Operation
    

    The first just displays the variables value, the second assigns the value of the current row to the variable.

    It's also important to have an ORDER BY clause, as the output is otherwise not deterministic.

    All this is put into a subquery just out of aesthetic reasons,... to filter out this

    , @prev := Operation
    

    column.

    0 讨论(0)
提交回复
热议问题