Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

sql - how to do lag operation in mysql

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 example

UID                        Operation
 1                         Logged-in
 2                         View content
 3                         Review

I want to use lag function so that my output would be as follows

UID                        Operation              Lagoperation
 1                         Logged-in                
 2                         View content           Logged-in
 3                         Review                 View content

Does Mysql support lag function???

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...