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".
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.
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?
41
need to be duplicated in theinventoried_items_group_id
column? I realise that you are comparing a set of two groups with a set of one and that you chose to store an expected ID and an inventoried ID on the same row for some reason, but then how would you be comparing e.g. 3 against 2? Or 2 against 3 for that matter? How would you decide which ID to duplicate? Wouldn't it be easier to use nulls (as in(39, 41), (40, NULL)
)? Even better, store all IDs in the same column and have an additional indicator column calledis_inventoried
(0 = expected, 1 = inventoried). Just a thought.n
groups. I should use=
instead ofIN
on the second subquery to indicate that.