Theory
Aggregation collapses a bag of solutions into one row per group. The moving parts:
GROUP BY ?key— partition rows by a key.- Aggregate functions —
COUNT,SUM,AVG,MIN,MAX,SAMPLE,GROUP_CONCAT. HAVING(expr)— likeFILTER, but applied after grouping, on aggregate values.
SELECT ?master (COUNT(?ninja) AS ?students) WHERE {
?master :teaches ?ninja .
}
GROUP BY ?master
HAVING (COUNT(?ninja) >= 2)
ORDER BY DESC(?students)
The rules that cause 'not a valid aggregate' errors
- Every non-aggregated projected variable must appear in
GROUP BY. You can'tSELECT ?master ?ninja (COUNT...)and group only by?master;?ninjamust be inside an aggregate or in theGROUP BY. COUNT(?x)counts bound values;COUNT(DISTINCT ?x)de-dupes;COUNT(*)counts rows. Picking the wrong one is the classic 'my numbers are too high' bug — usually you wantDISTINCT.- Filter rows with
FILTER(before grouping), filter groups withHAVING(after). Putting an aggregate in aFILTERis illegal.