Get entries with related to selected categories and then group by category Background:

I have a listing overview page that lists teaching staff grouped by their department (A category group holds all departments). E.g.

All Staff Members:

-- Science --
    Mrs Magnesium
    Mr Bunson

 -- P.E --
    Mr Stretch
    Mrs Bend

-- Maths -- 
    Ms Multiplication
    Mr Trig


To achieve the above I am using this code, which is working perfectly on a single page:

{% set entries = craft.entries.section('staffMembers').with(['staffPhoto']).all() %}
{% for category, catEntries in entries | group('staffGroup.one().title') %}
    &lt;div&gt;
    {% for entry in catEntries %}                
        &lt;h3&gt;{{ entry.staffTitle }}&lt;/h3&gt;  
        &lt;p&gt;{{ entry.staffBio }}&lt;/p&gt;     
    {% endfor %}
    &lt;/div&gt;
{% endfor %}


Question:

The client now needs to split these staff members across different pages, like the example below. So in order to achieve this I want them to be able use a category field (entry.staffGroups) where they can select multiple categories (departments) to display on each page. Hope I am making sense!

Science Staff Page:

-- Science --
    Mrs Magnesium
    Mr Bunson


Physical Education Staff Page:

 -- P.E --
    Mr Stretch
    Mrs Bend


Mathematics Staff Page

-- Maths -- 
    Ms Multiplication
    Mr Trig


I am struggling to achieve this, my attempt is below:

{# get the selected categories (departments) from category field #}
{% set departments = entry.allDepartments.all() %}

{# Set the entries, and attempt to relate them to ONLY the selected departments.#}
{% set entries = craft.entries.section('staffMembers').relatedTo(departments|join(',')).with(['staffPhoto']).all() %}
    {% for category, catEntries in entries | group('staffGroup.one().title') %}
        &lt;div&gt;
        {% for entry in catEntries %}                
            &lt;h3&gt;{{ entry.staffTitle }}&lt;/h3&gt;  
            &lt;p&gt;{{ entry.staffBio }}&lt;/p&gt;     
        {% endfor %}
        &lt;/div&gt;
    {% endfor %}


Example of entry:



Thanks!!
I may not understand fully, but it sounds like you could just loop over the attached Department Categories, then query for Staff related to that category:

{# Load the Departments Categories: #}
{% set departments = entry.allDepartments.all() %}

{% for department in departments %}
  {# Find all the Staff Members associated with the department: #}
  {% set staff = craft.entries({
    section: 'staffMembers',
    relatedTo: department,
    with: ['staffPhoto']
  }).all() %}

  &lt;h1&gt;{{ department.title }}&lt;/h1&gt;
  &lt;ul&gt;
    {# Loop over the Staff Members: #}
    {% for person in staff %}
      &lt;li&gt;{{ person.title }}&lt;/li&gt;
    {% endfor %}
  &lt;/ul&gt;
{% endfor %}



  There is a (very slight) performance penalty for performing queries like this in a loop, but it sounds like each of these focused sub-pages won't have too many Departments listed anyway.