Repository navigation
Description
Problem
A.aggr(B, ...) keeps every row of A by default, using a LEFT JOIN. For a row of A with no match, the left join supplies one row padded with NULLs, and COUNT(*) counts it. So A.aggr(B, n="count(*)") reports n = 1 for entities that have no matches.
The docstring example therefore shows 1, not 0, for subjects without sessions:
Subject.aggr(Session, n="count(*)") # keeps all subjects, even those with 0 sessionsReproduction
DataJoint 2.3.5.dev, MySQL 8.0, using the same two tables as #1708 (subject 2 has no sessions):
>>> Subject.aggr(Session, n="count(*)").to_dicts()
[{'subject_id': 1, 'n': 2}, {'subject_id': 2, 'n': 1}] # should be 0
>>> Subject.aggr(Session, n="count(session)").to_dicts()
[{'subject_id': 1, 'n': 2}, {'subject_id': 2, 'n': 0}] # correctProposal
Rewrite count(*) in an aggregation over a group B as a count of a column that is null only in the padding: B's own copy of a primary-key attribute, which is always non-null.
Two points need care:
- Shared key attributes. With
USING-style joins, the key attributesBshares withAare merged withA's values, so they are non-null even in the padded row. The count must referenceB's own copy inside the subquery. - All of
B's key shared withA. WhenAandBare one-to-one,Bhas no key attribute of its own to count. In that case, count a marker column (1 AS _present) added toB.
Apply the rewrite whenever rows are kept (the default). Applying it uniformly is also harmless for exclude_nonmatching=True and dj.U(...).aggr.
Other aggregates (sum, avg, min, max, count(col)) already ignore the padded row when they read columns only B has. If an aggregate reads a column shared with A, it sees A's value on the padded row; document this.
Tests
- The count is 0 for entities with no matches when
B's key extendsA's key. - The count is 0 for entities with no matches when
AandBare one-to-one (the marker-column case). count(*)andcount(distinct ...)give correct results on restricted groups (see aggr: a restricted group drops the rows with no match, though aggr keeps all rows by default #1650 and fix: aggr, extend and union keep unmatched rows when the right operand is restricted #1655).
Activity