1

I have more records of the same subject and predicate, but different object, like:

Alex hasFriend A
Alex hasFriend B
Alex hasFriend C
Alex hasFriend D

How could I query the data to get the result with comma separated values, like:

Alex hasFriend A, B, C, D

The SPARQL query is like this:

select distinct ?person ?friend where {

?person <http://www.example.com/hasFriend> ?friend.
  
}
Ian Kurtis
  • 137
  • 7
  • 1
    you have to group by and apply an aggregate function: `select ?person (group_concat(?friend; separator=', ') as ?friends) where { ?person ?friend. } group by ?person` – UninformedUser Oct 29 '21 at 14:42
  • 1
    I was about to add an answer but saw you had already answered in a comment @UninformedUser. Would you care to add an answer so that others can see the question has an answer? I'm happy to do it also but as you answered first did not want to without asking first. – Kelvin Lawrence Oct 29 '21 at 16:38

1 Answers1

3

Adding an answer to summarize the comment section above. The GROUP_CONCAT aggregate function can be used to achieve the results you are looking for. Note that the function allows you to specify the delimiter of your choice.

SELECT ?person (GROUP_CONCAT(?friend; separator=', ') AS ?friends) 
WHERE
{  
  ?person <http://www.example.com/hasFriend> ?friend 
} 
GROUP BY ?person
Kelvin Lawrence
  • 14,674
  • 2
  • 16
  • 38