Looking for help with SQL query!
I have 2 tables, A and B. Both tables have the column ‘student_id’ and ‘created_date’. For table A, ‘created_date’ is null but I wish to populate it with data from table B.
In table B, there are multiple of the same ‘student_id’ values, so I am trying to fetch only the one that has the earliest ‘created_date’.
Once I get that date, I want to then go back to table A, look for that exact same ‘student_id’ and then insert that MIN ‘created_date’ into table A.
If anybody could help that would be greatly appreciated!
UPDATE student as A INNER JOIN (SELECT MIN(student_registration.created_date) mindate, student_id FROM student_registration GROUP By student_id ) B ON A.student_id = B.student_id SET A.`created_date` = B.mindate WHERE A.`created_date` is null;
Advertisement
Answer
You can make something like this
Update Tablea A inner join (SELECT MIN(`created_date`) mindate, student_id FROM Tableb GROUP By student_id ) B On A.student_id = B.student_id Set A.`created_date` = B.mindate Where A.`created_date` is NULL ;
With the inner join you find the minimal Date in TableB and it is the right one for the student_id.
The rest is simple Updatelogic.
With the Where Clause at the end you can select only the rows that you need.
For Postgresql is the query like this
UPDATE student as A SET created_date = B.mindate FROM (Select MIN(created_date) as mindate, student_id From student_registration GROUP BY student_id) as B WHERE A.student_id = B.student_id AND A.created_date is null;