How to query to get comma separated values if the subject is the same?

314 Views Asked by At

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.
  
}
1

There are 1 best solutions below

0
Kelvin Lawrence On

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