0

I am trying to query all the cats breeds (wd:Q43577) along with the list of cats that belong to. Below, you will find my solution. The result of my solution is not relevant and contains a redundancy. Therefore, I need your help to find the best solution. (to execute this query, you have to use this link).

     SELECT ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName ?CatsID ?CatsName  where {
     ?CatsBreedsID wdt:P31 wd:Q43577.
    OPTIONAL{

                ?CatsBreedsID wdt:P279 ?CategoryID.
                ?CatsID       wdt:P31  ?CategoryID.
            }
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en".
            ?CatsBreedsID rdfs:label ?CatsBreedsName .
            ?CategoryID      rdfs:label ?CategoryName .
            ?CatsID      rdfs:label ?CatsName. 
    }    
    }
rfkortekaas
  • 6,049
  • 2
  • 27
  • 34
bilalox
  • 3
  • 1
  • 1

1 Answers1

2

You should use the GROUP_CONCAT function if I understand your question correctly.

Try a query like this:

    SELECT ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName
           (GROUP_CONCAT(DISTINCT ?CatsID; SEPARATOR=', ') AS ?CatsID_List)
           (GROUP_CONCAT(DISTINCT ?CatsName; SEPARATOR=', ') AS ?CatsName_List)
WHERE {
     ?CatsBreedsID wdt:P31 wd:Q43577.
    OPTIONAL{

                ?CatsBreedsID wdt:P279 ?CategoryID.
                ?CatsID       wdt:P31  ?CategoryID.
            }
    SERVICE wikibase:label {
        bd:serviceParam wikibase:language "en".
            ?CatsBreedsID rdfs:label ?CatsBreedsName .
            ?CategoryID      rdfs:label ?CategoryName .
            ?CatsID      rdfs:label ?CatsName. 
    }    
    } GROUP BY ?CatsBreedsID ?CatsBreedsName ?CategoryID ?CategoryName
Valerio Cocchi
  • 1,891
  • 1
  • 6
  • 18
  • 1
    I would not do it this way given that you will lose the relation between the catID (aka the Wikidata URI of the cat entity) and its label - there is no guaranteed order when doing `GROUP_CONCAT`. If you really want the URI and it's label, you should `CONCAT` both before, like this `(GROUP_CONCAT(DISTINCT CONCAT(str(?CatsID), CONCAT(" (", CONCAT(?CatsName, ")"))); SEPARATOR=', ') AS ?CatsID_List)` – UninformedUser Jun 01 '20 at 15:08