Parash Nath Mishra
Parash Nath Mishra

Reputation: 63

How to use SPARQL query to get field and field count at the same time?

I am new to Semantic Web and SPARQL. I am making a RDFS of concert. It has songs entries like:

con:song04
    rdfs:Class con:Repertoire;
    rdfs:label "Deewani Mastani";
    con:performedBy con:artist02.
    con:performedBy con:artist05.

I am trying to get list of songs and their count, if they are performed by same artist. I have been trying some tutorials from stackoverflow but does not server my purpose.

The query I am using might be wrong completely, would be really helpful in learning, if someone could help me on this aspects. I am using Apache Jena Fuseki to query.

PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX co: <http://rhizomik.net/ontologies/copyrightonto.owl#>
PREFIX dc: <http://purl.org/dc/elements/1.1/>
prefix con: <http://www.example.com/paras/concert#>

#Use SPARQL to count and list the songs that two artists share.
SELECT ?songs (COUNT(?artist) AS ?count)  
WHERE
{ 
  ?s rdfs:label ?songs .
  ?s rdf:type con:Repertoire.
  ?s con:performedBy ?artist.
  ?artist rdf:type con:Artist .
  filter( ?count > 1 )
}

Upvotes: 2

Views: 641

Answers (2)

Suresh KUMAR Mukhiya
Suresh KUMAR Mukhiya

Reputation: 606

According to description given, I totally agree with @Joshua Taylor and believe what you are trying to do can be achieved by the query. Please check if your RDFS is okay.

SELECT ?songs (COUNT(?artist) AS ?count)  
WHERE
{ 
  ?s rdfs:label ?songs .
  ?s rdfs:Class con:Repertoire.
  ?s con:performedBy ?artist.
  ?artist rdfs:Class con:Artist .
}
GROUP BY ?songs
HAVING (?count > 1 )

Upvotes: 1

Joshua Taylor
Joshua Taylor

Reputation: 85813

SELECT ?songs (COUNT(?artist) AS ?count)  
WHERE
{ 
  ?s rdfs:label ?songs .
  ?s rdfs:Class con:Repertoire.
  ?s con:performedBy ?artist.
  ?artist rdfs:Class con:Artist .
  filter( ?count > 1 )
}

If you paste that query into the validator at sparql.org, you see that it's an error to SELECT a variable that you haven't GROUPed BY when you're using aggregate functions like COUNT. Your query is almost correct though. You're trying to GROUP BY the song, and COUNT how many artists did that song. Then you want to take only the results HAVING a count greater than 1. You do that like this:

SELECT ?songs (COUNT(?artist) AS ?count)  
WHERE
{ 
  ?s rdfs:label ?songs .
  ?s rdfs:Class con:Repertoire.
  ?s con:performedBy ?artist.
  ?artist rdfs:Class con:Artist .
}
GROUP BY ?songs
HAVING (?count > 1 )

Upvotes: 2

Related Questions