41
| 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  
9
  • Are there only two per company? or is it variable? Jul 3, 2012 at 1:58
  • I see you have two companies here, but are there only ever two rows per company? If so you can use MAX() - MIN() aggregates trivially. If there are more than 2 rows per company, it is more complicated. Jul 3, 2012 at 2:01
  • I just need the latest two timestamp.. may be there are lot of entries for the same company but i just need to take the latest two time stamp and print the diff of quotes
    – javanx
    Jul 3, 2012 at 2:02
  • If a company is represented by only one row, would you like to return that company in the results? If so, what difference should be returned for it?
    – Andriy M
    Jul 3, 2012 at 8:01
  • 1
    In your example, why isn't the result negative for one of the companies? Google goes from 40 up to 60 whereas SAP goes from 60 down to 20. sqlfiddle.com/#!2/b62e1/1/0 Or do you only want the absolute movement irrespective of direction (in which case take ABS(delta))?
    – eggyal
    Jul 3, 2012 at 8:48

3 Answers 3

61

This is my favorite MySQL hack.

This is how you emulate the lag function:

SET @quot=-1;
select time,company,@quot lag_quote, @quot:=quote curr_quote
  from stocks order by company,time;
  • 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:

  1. order by clause is important here just like it is in a regular window function.
  2. You might also want to use lag for company just to be sure that you are computing difference in quotes of the same company.
  3. You can also implement row counters in the same way @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:

SET @quot=0,@latest=0,company='';
select B.* from (
select A.time,A.change,IF(@comp<>A.company,1,0) as LATEST,@comp:=A.company as company from (
select time,company,quote-@quot as change, @quot:=quote curr_quote
from stocks order by company,time) A
order by company,time desc) B where B.LATEST=1;

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.

8
  • I am getting error. DDL and DML statements are not allowed in the query panel for MySQL; only SELECT statements are allowed. Put DDL and DML in the schema panel.
    – javanx
    Jul 3, 2012 at 17:51
  • Though the error does not indicate this, try enabling "allowMultiQueries". This is a connector paramenter. For JDBC connector, see: dev.mysql.com/doc/refman/5.1/en/… . Are you able to run it successfully from MySQL client?
    – Dojo
    Jul 3, 2012 at 17:59
  • You can also try executing the two statements individually but in the same session.
    – Dojo
    Jul 3, 2012 at 18:02
  • 14
    @javanx Hi, I'm the author of SQL Fiddle. The error message you mention was actually a bug in the way I was handling certain types of MySQL queries. Thanks to your message here, I recognized it as such and have worked out a solution that fixes it (see here, for example: sqlfiddle.com/#!2/4f8a1/2). Thanks! Jul 4, 2012 at 5:03
  • 2
    NOTE You have to keep the data type of the variable consistent with the type of data you are trying to lag. EG, if you want to accumulate a FLOAT field, you must initialize your variable as @quot=0.0, otherwise it will not work. Took me a minute to figure this out! Nov 15, 2019 at 16:40
13

From MySQL 8.0 and above there is no need to simulate LAG. It is natively supported,

Window Function :

Returns the value of expr from the row that lags (precedes) the current row by N rows within its partition. If there is no such row, the return value is default. For example, if N is 3, the return value is default for the first two rows. If N or default are missing, the defaults are 1 and NULL, respectively.

SELECT
     company,
     quote,
     LAG(quote) OVER(PARTITION BY company ORDER BY time) AS prev_quote
FROM tab;

DBFiddle Demo

9

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:

SELECT c.company, c.mts, max(l.ts) AS lts
  FROM (SELECT company, max(ts) AS mts FROM cq GROUP BY company) AS c
  LEFT JOIN cq l
    ON c.company = l.company AND c.mts > l.ts
 GROUP BY c.company, c.mts;

Now you have to join this subquery with the original table to get the desired results:

SELECT c.company, l.quote, coalesce(l1.quote, 0),
       (l.quote - coalesce(l1.quote, 0)) AS result
  FROM (SELECT c.company, c.mts, max(l.ts) AS lts
      FROM (SELECT company, max(ts) AS mts FROM cq GROUP BY company) AS c
      LEFT JOIN cq l
        ON c.company = l.company AND c.mts > l.ts
     GROUP BY c.company, c.mts) AS c
  LEFT JOIN cq AS l ON l.company = c.company AND l.ts = c.mts
  LEFT JOIN cq AS l1 ON l1.company = c.company AND l1.ts = c.lts;

You can observe results on SQL Fiddle.

This query is using only standard SQL capabilities and should work on any RDBMS.

1
  • Good answer, especially for people preparing for tech interviews since they often discourage using window functions.
    – Evan Zamir
    Apr 19, 2021 at 13:13

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.