You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
aggr: count(*) reports 1 for entities with no matches #1709
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 sessions
Reproduction
DataJoint 2.3.5.dev, MySQL 8.0, using the same two tables as #1708 (subject 2 has no sessions):
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 attributes B shares with A are merged with A's values, so they are non-null even in the padded row. The count must reference B's own copy inside the subquery.
All of B's key shared with A. When A and B are one-to-one, B has no key attribute of its own to count. In that case, count a marker column (1 AS _present) added to B.
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 extends A's key.
The count is 0 for entities with no matches when A and B are one-to-one (the marker-column case).
Activity