| 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 I do a lag on this table in MySQL to print the difference in quotes, for example:
GOOGLE | 20
SAP | 40
To achieve the desired result, first you need to find the last and next to last timestamps for each company. It is quite simple with the following query:
Now you have to join this subquery with the original table to get the desired results:
You can observe results on SQL Fiddle.
This query is using only standard SQL capabilities and should work on any RDBMS.
This is my favorite MySQL hack.
This is how you emulate the lag function:
lag_quote
holds the value of previous row's quote. For the first row @quot is -1.curr_quote
holds the value of current row's quote.Notes:
order by
clause is important here just like it is in a regular window function.company
just to be sure that you are computing difference in quotes of the samecompany
.@cnt:=@cnt+1
The nice thing about this scheme is that is computationally very lean compared to some other approaches like using aggregate functions, stored procedures or processing data in application server.
EDIT:
Now coming to your question of getting result in the format you mentioned:
The nesting is not co-related so not as bad (computationally) as it looks (syntactically) :)
Let me know if you need any help with this.
From MySQL 8.0 and above there is no need to simulate
LAG
. It is natively supported,DBFiddle Demo