Reputation: 77
mysql> select * from FinalTable;
+------+-------+-------+---------------------+
| id | name | state | timestamp |
+------+-------+-------+---------------------+
| 12 | name1 | TX | 2020-01-25 11:29:36 |
| 14 | name3 | CA | 2020-01-25 11:29:36 |
| 14 | name3 | TX | 2020-01-25 11:29:36 |
| 12 | name1 | CA | 2020-01-25 11:29:36 |
| 13 | name2 | TA | 2020-01-25 11:29:36 |
| 14 | name3 | CA | 2020-01-25 11:29:36 |
+------+-------+-------+---------------------+
I am looking at output query which gives response as:
I2 name1 TX 2020-01-25 11:29:36 CA 2020-01-25 11:29:36
when I run the query,
select id,name,state,timestamp,
lead(state,1) over (partition by id order by timestamp asc) out_state,
lead(timestamp,1) over (partition by id order by timestamp asc) out_timestamp
from FinalTable
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(partition by id order by timestamp asc) out_state,
lead(timestamp,1) over (part' at line 2
also is it possible to create timetamp upto milliseconds instead of seconds in DB? I am using CURRENT_TIMESTAMP.
Upvotes: 0
Views: 729
Reputation: 222382
Window functions (such as lead()
) were added in MySQL 8.0 only, so they are not available in version 5.7. You can emulate lead()
with a self-join like so:
select t.*, tlead.state, tlead.timestamp
from FinalTable t
left join FinalTable tlead
on tlead .id = t.id
and tlead.timestamp = (
select min(t1.timestamp)
from FinalTable t1
where t1.id = t.id and t1.timestamp > t.timestamp
)
Side note: for this method to work properly, you need subsequent records of the same id
to have different timestamp
s - which is not the case in the sample data that you showed, where all timestamps are the same (I assume this is a typo in your sample data).
Upvotes: 1