diff --git a/calendar/classes/local/event/strategies/raw_event_retrieval_strategy.php b/calendar/classes/local/event/strategies/raw_event_retrieval_strategy.php
index 46b42d78..4e5fd61b 100644
--- a/calendar/classes/local/event/strategies/raw_event_retrieval_strategy.php
+++ b/calendar/classes/local/event/strategies/raw_event_retrieval_strategy.php
@@ -179,6 +179,9 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
         $whereclause = implode(' AND ', $whereconditions);
 
         // Build SQL subquery and conditions for filtered events based on priorities.
+        $subquerytimeconditions = array_filter($whereconditions, function($condition) {
+            return (strpos($condition, 'time') !== false);
+        });
         $subquerywhere = '';
         $subqueryconditions = [];
         $subqueryparams = [];
@@ -194,7 +197,12 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
                 // Set calendar filters.
                 list($usercourses, $usergroups, $user) = calendar_set_filters($usercourses, true, $userrecord);
 
-                $allusercourses = array_merge($allusercourses, $usercourses);
+                $filteredcourses = is_array($courses) ? $courses : [$courses];
+                $filteredcourses = array_filter($usercourses, function($course) use ($filteredcourses) {
+                    return in_array($course, $filteredcourses);
+                });
+
+                $allusercourses = array_merge($allusercourses, $filteredcourses);
 
                 // Flag to indicate whether the query needs to exclude group overrides.
                 $viewgroupsonly = false;
@@ -203,8 +211,15 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
                     // Set filter condition for the user's events.
                     // Even though $user is a single scalar, we still use get_in_or_equal() because we are inside a loop.
                     list($inusers, $inuserparams) = $DB->get_in_or_equal($user, SQL_PARAMS_NAMED);
-                    $subqueryconditions[] = "(ev.userid $inusers AND ev.courseid = 0 AND ev.groupid = 0 AND ev.categoryid = 0)";
-                    $subqueryparams = array_merge($subqueryparams, $inuserparams);
+                    if (empty($subquerytimeconditions)) {
+                        $subqueryconditions[] = "(ev.userid $inusers AND ev.courseid = 0 AND ev.groupid = 0 AND ev.categoryid = 0)";
+                        $subqueryparams = array_merge($subqueryparams, $inuserparams);
+                    } else {
+                        $subtimes = $this->subquerytimeconditions("user{$userrecord->id}", $subquerytimeconditions, $whereparams);
+                        $subqueryconditions[] = "(ev.userid $inusers AND ev.courseid = 0 AND ev.groupid = 0 AND ev.categoryid = 0)" .
+                            $subtimes['where'];
+                        $subqueryparams = array_merge($subqueryparams, $inuserparams, $subtimes['params']);
+                    }
 
                     foreach ($usercourses as $courseid) {
                         if (has_capability('moodle/site:accessallgroups', \context_course::instance($courseid), $userrecord)) {
@@ -263,8 +278,15 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
         // Set subquery filter condition for the courses.
         if (!empty($subquerycourses)) {
             list($incourses, $incoursesparams) = $DB->get_in_or_equal($subquerycourses, SQL_PARAMS_NAMED);
-            $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid $incourses AND ev.categoryid = 0)";
-            $subqueryparams = array_merge($subqueryparams, $incoursesparams);
+            if (empty($subquerytimeconditions)) {
+                $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid $incourses AND ev.categoryid = 0)";
+                $subqueryparams = array_merge($subqueryparams, $incoursesparams);
+            } else {
+                $subtimes = $this->subquerytimeconditions("courses", $subquerytimeconditions, $whereparams);
+                $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid $incourses AND ev.categoryid = 0)" .
+                            $subtimes['where'];
+                $subqueryparams = array_merge($subqueryparams, $incoursesparams, $subtimes['params']);
+            }
         }
 
         // Set subquery filter condition for the categories.
@@ -272,8 +294,15 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
             $subqueryconditions[] = "(ev.categoryid != 0 AND ev.eventtype = 'category')";
         } else if (!empty($categories)) {
             list($incategories, $incategoriesparams) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
-            $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid = 0 AND ev.categoryid $incategories)";
-            $subqueryparams = array_merge($subqueryparams, $incategoriesparams);
+            if (empty($subquerytimeconditions)) {
+                $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid = 0 AND ev.categoryid $incategories)";
+                $subqueryparams = array_merge($subqueryparams, $incategoriesparams);
+            } else {
+                $subtimes = $this->subquerytimeconditions("cats", $subquerytimeconditions, $whereparams);
+                $subqueryconditions[] = "(ev.groupid = 0 AND ev.courseid = 0 AND ev.categoryid $incategories)" .
+                            $subtimes['where'];
+                $subqueryparams = array_merge($subqueryparams, $incategoriesparams, $subtimes['params']);
+            }
         }
 
         // Build the WHERE condition for the sub-query.
@@ -282,6 +311,7 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
                                   FROM {event} ev
                                  WHERE ";
             $subqueryunion = '('.$unionstartquery . implode(" UNION $unionstartquery ", $subqueryconditions).')';
+            // $subquerywhere = 'WHERE ' . implode(" OR ", $subqueryconditions);
         } else {
             $subqueryunion = '{event}';
         }
@@ -298,6 +328,13 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
                             MIN(ev.priority) as priority
                        FROM $subqueryunion ev
                    GROUP BY ev.modulename, ev.instance, ev.eventtype";
+        // $subquery = "SELECT ev.modulename,
+        //                     ev.instance,
+        //                     ev.eventtype,
+        //                     MIN(ev.priority) as priority
+        //                     FROM {event} ev
+        //                 $subquerywhere
+        //             GROUP BY ev.modulename, ev.instance, ev.eventtype";
 
         // Build the main query.
         $sql = "SELECT e.*
@@ -320,4 +357,28 @@ class raw_event_retrieval_strategy implements raw_event_retrieval_strategy_inter
 
         return  $events === false ? [] : $events;
     }
+
+    protected function subquerytimeconditions($prefix, $conditions, $params) {
+        $outwhere = '';
+        $outparams = [];
+        // Most specific to least specific.
+        $timeparams = ['timefromid', 'timefrom3', 'timefrom2', 'timefrom1', 'timefrom', 'timetoid', 'timeto2', 'timeto1', 'timeto'];
+        $whereconditions = [];
+        foreach ($conditions as $condition) {
+            $where = $condition;
+            // This query has been borrowed from the main WHERE clause, so the alias needs to be renamed to match the union.
+            $where = str_replace('e.id', 'ev.id', $where);
+            foreach ($timeparams as $timeparam) {
+                if (isset($params[$timeparam])) {
+                    $where = str_replace(":{$timeparam}", ":{$prefix}{$timeparam}", $where);
+                    $outparams["{$prefix}{$timeparam}"] = $params[$timeparam];
+                }
+            }
+            $whereconditions[] = $where;
+        }
+        if (count($whereconditions) > 0) {
+            $outwhere = ' AND ' . implode(' AND ', $whereconditions);
+        }
+        return ['where' => $outwhere, 'params' => $outparams];
+    }
 }
