Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Over Clause getting syntax errors in sql

As got the answer from How to combine two sql queries to get a one table in mysql? here I have a database as follows and I need the output as below.

Time         Number  Updated
2/10/2022 10:12 12345     1    
2/11/2022 10:12 234       0    
2/12/2022 10:12 433       0    
2/13/2022 10:12 556       0    
2/14/2022 10:12 4357      0    
2/15/2022 10:12 12345     0

output:

Time            Number  Updated    Last Updated
2/10/2022 10:12 12345     1      2/15/2022 10:12
2/11/2022 10:12 234       0      2/11/2022 10:12
2/12/2022 10:12 433       0      2/12/2022 10:12
2/13/2022 10:12 556       0      2/13/2022 10:12
2/14/2022 10:12 4357      0      2/14/2022 10:12
2/15/2022 10:12 12345     0      2/15/2022 10:12

We can get the output by using following query,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT
    Time,
    Number,
    MAX(Time) OVER (PARTITION BY Number) AS LastUpdated
FROM yourTable
ORDER BY Time;

This works fine when I have used it in my localhost with php file. But when I am using this same query in my remote server I am getting syntax error as,

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....

Seems my mysql version in remote server(mysql Ver 14.14 Distrib 5.1.73) doesn’t support that. Can someone provide alternative way to do this same?

>Solution :

If your MySQL version didn’t support window function, You can try to use subquery with MAX to make it.

Query #1

SELECT
    Time,
    Number,
    (SELECT MAX(Time) FROM yourTable tt WHERE t.Number = tt.Number) LastUpdated
FROM yourTable t
ORDER BY Time;

or use ORDER BY with LIMIT to get the lastest each Number

SELECT
    Time,
    Number,
    (SELECT Time FROM yourTable tt WHERE t.Number = tt.Number ORDER BY Time DESC LIMIT 1) LastUpdated
FROM yourTable t
ORDER BY Time;
Time Number LastUpdated
2022-02-10 10:12:00 12345 2022-02-15 10:12:00
2022-02-11 10:12:00 234 2022-02-11 10:12:00
2022-02-12 10:12:00 433 2022-02-12 10:12:00
2022-02-13 10:12:00 556 2022-02-13 10:12:00
2022-02-14 10:12:00 4357 2022-02-14 10:12:00
2022-02-15 10:12:00 12345 2022-02-15 10:12:00
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading