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_quoteholds value of previous row's quote. first row @quot -1.curr_quoteholds value of current row's quote.
notes:
order byclause important here in regular window function.- you might want use lag
companysure computing difference in quotes of samecompany. - 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
Post a Comment