Many-to-many tables with aggregation

Dear CUBA team.

Can I ask you the best solution for the following idea.
I have three entity:

Each batch contains several items. The manager can create an order from items of different batches.
But each item can be used in several orders.

The entities Order and Items are created with associated fields with MANY-TO-MANY cardinality.

The goal is to create a table:

which contains info about orders by batches.

I’m trying to realize this via two nested tables Orders and Stats. The first to select an order, the second to display the aggregated order info. I plan to use Valued Collection Datasource with JPQL custom query, but I can’t compose a correct request to Items based on selected order. I’ve started with a simple select of items:

select i.number, count(
from demo$Item i
where = :ds$

Error: The state field path ‘’ cannot be resolved to a valid type.

What is the correct method to work with the many-to-many joined fields?
Or can you suggest another way?

Many thank’s to Даниил Царёв, the task was solved by request:

select i.batch.number, count(i)
from demo$Item i
where in
    (select from demo$Order os join os.items its where = :ds$ordersDs)
group by i.batch.number