Search code examples
sparqlmarklogicmarklogic-9

SPARQL for unique set of values from all columns and rows


I have a query that returns several columns, i.e.:

SELECT ?a ?b ?c
WHERE { ... }

Every column variable is an IRI. Obviously this returns a unique row for every combination of column values (note that values may not be unique to a column):

<urn:id:x:1> <urn:id:a:2> <urn:id:j:3>
<urn:id:x:1> <urn:id:a:2> <urn:id:j:4>
<urn:id:x:1> <urn:id:j:4> <urn:id:k:5>
<urn:id:y:2> <urn:id:j:4> <urn:id:k:6>
...

However, all I need are the unique IRIs spanning all rows and columns. i.e.:

<urn:id:x:1>
<urn:id:a:2>
<urn:id:j:3>
<urn:id:j:4>
<urn:id:k:5>
<urn:id:y:2>
<urn:id:k:6>
...

Is it possible to achieve this using SPARQL, or do I need to post-process the results to merge and de-deduplicate the values? Order is unimportant.


Solution

  • SELECT DISTINCT ?d {
        ...
        VALUES ?i { 1 2 3 }
        BIND (if(?i=1, ?a, if(?i=2, ?b, ?c)) AS ?d)
    }
    

    What does this do?

    1. The VALUES clause creates three copies of each solution and numbers them with a variable ?i
    2. The BIND clause creates a new variable ?d whose value is ?a, ?b or ?c, depending on whether ?i is 1, 2 or 3 in the given solution
    3. The SELECT DISTINCT ?d returns only ?d and removes duplicates