How to do a COUNT in SPARQL
Asked Answered
B

3

10

Given this very simple model:

@prefix :        <http://example.org/tags#> .
@prefix owl:     <http://www.w3.org/2002/07/owl#> .
@prefix rdf:     <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs:    <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd:     <http://www.w3.org/2001/XMLSchema#> .

:tag  rdf:type rdf:Property .

:item1
      rdf:type owl:Thing ;
      :tag    "a"^^xsd:string .

:item2
      rdf:type owl:Thing ;
      :tag    "a"^^xsd:string , "b"^^xsd:string .

:item3
      rdf:type owl:Thing ;
      :tag    "a"^^xsd:string , "b"^^xsd:string , "c"^^xsd:string .

I am trying to get a list of the items and the count of tags that each has:

item  tagCount
===== ========
item1 1
item2 2
item3 3

Here is my query:

SELECT ?item (count(?tag) as ?tagcount)
WHERE {
     ?item :tag ?tag
}

However it is returning:

item  tagCount
===== ========
      6

From what I have read, this should work. I am using Jena 2.6.4

Baldwin answered 3/5, 2012 at 22:54 Comment(2)
COUNT is not a part of the SPARQL 1.0 specification, it was added in 1.1. Some implementations support it despite that. Just saying.Rote
Upvoted for clearly expressed question and proper formatting!Houck
H
7

I haven't tried this, but try adding GROUP BY ?item to the end of the query. I think without GROUP BY it just counts the total number of rows.

Houck answered 4/5, 2012 at 0:30 Comment(1)
Yes, it counts the total number of rows. It's exactly the same as what SQL does too in this case. However, I don't know what happens with ?item.Adoration
B
4

For the binding to appear in the results you do need to use the group by keyword so this becomes

SELECT ?item (count(?tag) as ?tagcount) WHERE { ?item :tag ?tag } group by ?item

If you want to count something in the middle of the query you would do the following, note how you must put the inner select query into its own block {}

SELECT * {
    ?item a owl:Thing .

    {
        SELECT ?item (count(?tag) as ?tagcount)
        WHERE {
             ?item :tag ?tag
        } group by ?item
    } 
}
Brandebrandea answered 24/4, 2013 at 15:27 Comment(0)
A
0

The sub-select by @user2316243 is unnecessary, therefore the following query is equivalent:

SELECT ?item (count(?tag) as ?tagcount)
WHERE {
   ?item a owl:Thing .
   ?item :tag ?tag .
} GROUP BY ?item
Applegate answered 22/4, 2016 at 16:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.