结合SPARQL查询

时间:2018-12-16 09:43:47

标签: sparql

我想获取人口最多和人口最少的州的人口。我知道如何使用ORDER BYASCDESC)。如何在单个查询中组合这两个(ASCDESC)?

SELECT  ?population
{
?state rdf:type :State
?state :hasPopulation ?population.
} ORDER BY DESC(?population) LIMIT 1
AND

SELECT  ?population
{
?state rdf:type :State
?state :hasPopulation ?population.
} ORDER BY ASC(?population) LIMIT 1

2 个答案:

答案 0 :(得分:4)

SELECT ?population_max ?population_min {
    ?state_max rdf:type :State .
    ?state_max :hasPopulation ?population_max .
    ?state_min rdf:type :State .
    ?state_min :hasPopulation ?population_min .
} ORDER BY DESC(?population_max) ASC(?population_min) LIMIT 1

也许更有效:

SELECT * {
    {
        SELECT (?population AS ?population_max) {
            ?state rdf:type :State .
            ?state :hasPopulation ?population .
        } ORDER BY DESC(?population) LIMIT 1 
    }
    {
        SELECT (?population AS ?population_min) {
            ?state rdf:type :State .
            ?state :hasPopulation ?population .
        } ORDER BY ASC(?population) LIMIT 1
    }
}

在AnzoGraph或Blazegraph的情况下,可以使用named subqueries

SELECT *
WITH {
    SELECT ?pop { [] a :State ; :hasPopulation ?pop }
} AS %unsorted
WHERE {
    { SELECT (?pop AS ?max) { INCLUDE %unsorted } ORDER BY DESC(?pop) LIMIT 1 }
    { SELECT (?pop AS ?min) { INCLUDE %unsorted } ORDER BY  ASC(?pop) LIMIT 1 }
}

最后,是重写而不是合并:

SELECT (MAX(?population) AS ?population_max) (MIN(?population) AS ?population_min) {
    ?state rdf:type :State .
    ?state :hasPopulation ?population
} 
  

如果使用聚合...但是不使用GROUP BY术语,则将其视为所有解决方案所属的单个隐式组。

答案 1 :(得分:0)

您也许可以使用UNION组合“最大”和“最小”人口。这是AnzoGraph语法:

Table_A
Table_A_