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

How to put value from another column instead of null for nearest date?

I do have next table structure on mysql server:

person_id   company_id  time_of_registration
12          333         2022-02-15 8:03:00
13          333         2022-02-15 8:04:00
14          NULL        2022-02-15 8:10:00
15          333         2022-02-15 8:10:00
16          NULL        2022-02-15 8:12:30
17          222         2022-02-15 8:14:00
18          NULL        2022-02-15 8:23:00
19          111         2022-02-15 11:04:00

I would like to put nearest company_id (by time_of_registration) if there is null in the company_id column.

Desired output is:

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

person_id   company_id  time_of_registration
12          333         2022-02-15 8:03:00
13          333         2022-02-15 8:04:00
14          333         2022-02-15 8:10:00
15          333         2022-02-15 8:10:00
16          222         2022-02-15 8:12:30
17          222         2022-02-15 8:14:00
18          222         2022-02-15 8:23:00
19          111         2022-02-15 11:04:00

Thanks in advance.

>Solution :

You can use COALESCE() to default the value to a user variable which is set by a side-effect assignment expression. Something like the following:

SELECT person_id,
 @cmp := COALESCE(company_id, @cmp) AS company_id,
FROM MyTable
ORDER BY time_of_registration;
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