I have pretty hard query to write and I have no idea how to approach this.

I also have no idea for my question title, so if someone has good idea how to describe my problem - please suggest it.

---

I'm working on software for stock management and I need a query that will show all differences between "Expected groups" and "Inventoried group".

There is `inventory_item_stocktakings` table that holds data about Stocktaking.
It is related with `inventory_item_groups` table, which is a table used to group `inventory_items` for many different purposes.
Each "Stocktaking" can be made of multiple `inventory_item_stocktakings` records. For example this is a "Stocktaking" performed on 2 source groups (39, 40) with "Expected items" and there is one result group (41) for "Inventoried items".

[![enter image description here](https://i.stack.imgur.com/OD5SK.png)](https://i.stack.imgur.com/OD5SK.png)

To get differences between "Expected items" and "Inventoried items" I have written this query:

```
select * from
    (select inventory_item_group_id, inventory_item_id from inventory_item_group_items where inventory_item_group_id in (39, 40)) e
RIGHT JOIN 
    (select inventory_item_group_id, inventory_item_id from inventory_item_group_items where inventory_item_group_id in (41)) i
on e.inventory_item_id = i.inventory_item_id
where e.inventory_item_id is null
UNION 
select * from
    (select inventory_item_group_id, inventory_item_id from inventory_item_group_items where inventory_item_group_id in (39, 40)) e
LEFT JOIN 
    (select inventory_item_group_id, inventory_item_id from inventory_item_group_items where inventory_item_group_id in (41)) i
on e.inventory_item_id = i.inventory_item_id
where i.inventory_item_id is null

```

This is the result "Stocktaking" performed on 39 and 40 grops, with results stored in 41 group and there are 6 missing items and 2 unexpected items.

[![enter image description here](https://i.stack.imgur.com/Frp6G.png)](https://i.stack.imgur.com/Frp6G.png)

However this cannot be parametrized (notice hardcoded 39, 40 and 41 group id's).

How can extend this query to show all differences from all existing stoctakings?