sql - Simulate lag function in MySQL -


| time                | company | quote | +---------------------+---------+-------+ | 0000-00-00 00:00:00 | google  |    40 | | 2012-07-02 21:28:05 | google  |    60 | | 2012-07-02 21:28:51 | sap     |    60 | | 2012-07-02 21:29:05 | sap     |    20 | 

how do lag on table in mysql print difference in quotes, example:

google | 20 sap    | 40   

this favorite mysql hack.

this how emulate lag function:

set @quot=-1; select time,company,@quot lag_quote, @quot:=quote curr_quote   stocks order company,time; 
  • lag_quote holds value of previous row's quote. first row @quot -1.
  • curr_quote holds value of current row's quote.

notes:

  1. order by clause important here in regular window function.
  2. you might want use lag company sure computing difference in quotes of same company.
  3. you can implement row counters in same way @cnt:=@cnt+1

the nice thing scheme is computationally lean compared other approaches using aggregate functions, stored procedures or processing data in application server.

edit:

now coming question of getting result in format mentioned:

set @quot=0,@latest=0,company=''; select b.* ( select a.time,a.change,if(@comp<>a.company,1,0) latest,@comp:=a.company company ( select time,company,quote-@quot change, @quot:=quote curr_quote stocks order company,time) order company,time desc) b b.latest=1; 

the nesting not co-related not bad (computationally) looks (syntactically) :)

let me know if need this.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -