MySQL Forums
Forum List  »  Newbie

Re: Oracle Analytical Functions
Posted by: Rick James
Date: May 30, 2009 05:56PM

Lead() and lag() do not exist. You can simulate that by creating a tmp table with an auto_increment id, plus the rows of interest. Then do a self-join(s).

CREATE TEMPORARY TABLE tmp (
    id INT UNSIGNED AUTO_INCREMENT NOT NULL,
    value ...,
    PRIMARY KEY (id)
);
INSERT INTO tmp (value)
    SELECT value FROM original_table
       ORDER BY ...;

SELECT a.value as lead1,
       b.value,
       c.value as lag2
   FROM tmp a, tmp b, tmp c
   WHERE a.id = b.id-1
     AND c.id = b.id+2;
But, alas, you will get
ERROR 1137 (HY000): Can't reopen table: 'a'
So, don't make it a TEMPORARY TABLE.

for example:
Given this intermediate table (after adding the id)
+----+----------------+
| id | value          |
+----+----------------+
|  1 | broth          |
|  2 | fig            |
|  3 | fillet of beef |
|  4 | french fries   |
|  5 | herring        |
|  6 | leaves         |
|  7 | oil            |
|  8 | pumpkin        |
|  9 | small pie      |
| 10 | spaghetti      |
| 11 | squid          |
| 12 | thoroughly     |
| 13 | thyme          |
| 14 | whisk          |
+----+----------------+
14 rows in set (0.00 sec)
Here are the lead (by 1) and lag (by 2) examples
+----------------+----------------+--------------+
| lead1          | value          | lag2         |
+----------------+----------------+--------------+
| broth          | fig            | french fries |
| fig            | fillet of beef | herring      |
| fillet of beef | french fries   | leaves       |
| french fries   | herring        | oil          |
| herring        | leaves         | pumpkin      |
| leaves         | oil            | small pie    |
| oil            | pumpkin        | spaghetti    |
| pumpkin        | small pie      | squid        |
| small pie      | spaghetti      | thoroughly   |
| spaghetti      | squid          | thyme        |
| squid          | thoroughly     | whisk        |
+----------------+----------------+--------------+
11 rows in set (0.00 sec)
With LEFT/RIGHT JOINs, you could deal with the end cases.

Options: ReplyQuote


Subject
Written By
Posted
Re: Oracle Analytical Functions
May 30, 2009 05:56PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.