$wpdb->get_results returns an array of resultset rows and a foreach processes over an array, so the foreach does all the moving down an array, all you need to do is use the $row as the current row you are processing
$results = $wpdb->get_results ( "SELECT * FROM interestclass
where SortingCode='bake1r20210113' ||
SortingCode='bake1r20210225' ||
SortingCode='bake1r20210506' ||
SortingCode='bake1r20210612' ||
SortingCode='bake1r20210813'" );
foreach ( $results as $row ) {
echo "<td> working {$row->LessonCode}</td>";
}
Additional code as per your comment below.
So if you want to test this row against the next row in the array, a simple change to the format of the foreach will provide you with the key to the array. You can then use that on the $results array to gain access to the next occurance in the array. Be careful, its easy doing this to exceed the bounds of the array, so first you need to check that will not happen with a simple IF
$results = $wpdb->get_results ( "SELECT * FROM interestclass
where SortingCode='bake1r20210113' ||
SortingCode='bake1r20210225' ||
SortingCode='bake1r20210506' ||
SortingCode='bake1r20210612' ||
SortingCode='bake1r20210813'" );
$resultCount = count($results);
foreach ( $results as $key => $row ) {
// first make sure we have a next row
if ( $key < $resultCount ){
$nextRow = $results[$key+1];
if ( $row->LessonCode == $nextRow->LessonCode ) {
echo "<td> working {$row->LessonCode}</td>";
}
}
}