If the following result is the one you would expect …
topic_combination|incidence Test1*Test2*Test3|3 Demo1*Demo2|2 Probe1|1
… it is sufficient to replace …
let $incidence := count($topics)
… by …
let $incidence := count($x)
The string join yields a single item, which is assigned to $topics; thus, count($topics) returns 1. Grouped values will be assigned to the variables that have been declared before the 'group by' clause. This means that count($x) returns …
• 1 if it’s called before 'group by' • the number of grouped items if it’s called after 'group by'