0

The following query is working:

SELECT  ?goal (count(?ngo) as ?ngoCount)
WHERE {?ngo a ngo:NGORecipient;
            ngo:hasSDGGoal ?goal.
        ?goal rdfs:label ?sdglabel.}
            GROUP BY ?goal
            ORDER BY ?ngoCount

However, when I go to get the label rather than the IRI as follows

SELECT  ?sdglabel (count(?ngo) as ?ngoCount)
WHERE {?ngo a ngo:NGORecipient;
            ngo:hasSDGGoal ?goal.
        ?goal rdfs:label ?sdglabel.}
            GROUP BY ?goal
            ORDER BY ?ngoCount

I get an error: "Executing query failed: All selected variables must be aggregates but ?sdglabel is not."

  • 1
    when using grouping for all variables being projected you either have to i) enumerate the variables that denote (or build) the group or ii) use an aggregate function on it. That means, a) you could group by the label which could be error prone, b) also group by the label which might lead to multiple groups (and therefore rows) if there are multiple labels for the same entity or c) group by the entity and use an aggregate function on the label or d) group by the entity and the label – UninformedUser Aug 26 '23 at 06:15
  • 1
    for example `GROUP BY ?goal ?sdglabel`, but it fails if there are multiple labels. I'd suggest to use an aggregate on the label, e.g. `SELECT (SAMPLE(?sdglabel_) AS ?sdglabel) (COUNT(?ngo) as ?ngoCount) WHERE {?ngo a ngo:NGORecipient; ngo:hasSDGGoal ?goal. ?goal rdfs:label ?sdglabel_ .} GROUP BY ?goal ORDER BY ?ngoCount` – UninformedUser Aug 26 '23 at 06:17
  • 1
    if you're wondering about the `?sdglabel_`, in SPARQL you aren't allowed to reassign a variable in the projection part, so an "overwrite" like `(SAMPLE(?sdglabel) AS ?sdglabel)` isn'T possible – UninformedUser Aug 26 '23 at 06:19

1 Answers1

1

Thanks! This works fine:

SELECT  ?sdglabel (count(?ngo) as ?ngoCount)
WHERE {?ngo a ngo:NGORecipient;
            ngo:hasSDGGoal ?goal.
        ?goal rdfs:label ?sdglabel.}
            GROUP BY ?sdglabel
            ORDER BY ?ngoCount

I don't have to worry about IRIs with the same label because there shouldn't be any. If I'm understanding it would fail if there were but just to be sure I did a query to test for any SDGs with different IRIs but the same label and as I expected there aren't any.

  • 1
    it would not fail if you have multiple IRIs sharing the same label, but it would simply return a number of NGOs which would be wrong because it would be the sum of the count of all the NGOs with an SDG goal that has the same label. If you would have SDG `A1` and `A2` and for whatever reason the label is just `"SDG A"`, then the count would be the sum of the number of NGOs of `A1` and `A2` – UninformedUser Aug 29 '23 at 12:18