当您在投影中使用聚合时,您必须通过某些变量的不同值对解决方案进行分区或分组。如果您不指定 group by 子句,则分组是隐式的。在这种情况下,您有(至少)两个选择。一种是使用两个子查询,如:
select ?acount ?bcount (?acount + ?bcount as ?totalCount) where {
{ select (count(*) as ?acount) where {
graph :a { ... } }
{ select (count(*) as ?bcount) where {
graph :b { ... } }
}
我认为这可能是最简单、最不言自明的选项。正如您所指出的,另一种选择是使用联合:
select (count(?a) as ?acount)
(count(?b) as ?bcount)
(?acount + ?bcount as ?totalCount)
where {
{ graph :a { ?a ... } }
union
{ graph :b { ?b ... } }
}
类似的原因
select (count(?a) as ?acount)
(count(?b) as ?bcount)
(?acount + ?bcount as ?totalCount)
where {
graph :a { ?a ... }
graph :b { ?b ... }
}
不起作用是你最终得到 ?a 和 ?b 值的笛卡尔积。即,假设存在两个值的?a 和三个值的?b。然后你最终在表格中有六行:
a1, b1
a1, b2
a1, b3
a2, b1
a2, b2
a2, b3
这些行中的每一行都是唯一的,因此如果您使用隐式 group by,您将有六个 a 和六个 b,这并不是您真正想要的。但是,您仍然可以这样做,使用 distinct:
select (count(distinct ?a) as ?acount)
(count(distinct ?b) as ?bcount)
(?acount + ?bcount as ?totalCount)
where {
#-- ...
}
查询类型
类型 1:子查询
SELECT ?BScount ?NEcount (?BScount + ?NEcount as ?totalCount)
WHERE {
{ select (count(*) as ?BScount) WHERE {
GRAPH bs: { ?sBS a locah:ArchivalResource }
} }
{ select (count(*) as ?NEcount) WHERE {
GRAPH ne: { ?sNE a locah:ArchivalResource }
} }
}
类型 2:联合
SELECT (count(?sBS) as ?BScount)
(count(?sNE) AS ?NEcount)
(?BScount + ?NEcount as ?totalCount)
WHERE {
{ GRAPH bs: { ?sBS a locah:ArchivalResource } }
UNION
{ GRAPH ne: { ?sNE a locah:ArchivalResource } }
}
类型 3:笛卡尔积和相异
SELECT (count(distinct ?sBS) as ?BScount)
(count(distinct ?sNE) AS ?NEcount)
(?BScount + ?NEcount as ?totalCount)
WHERE {
{ GRAPH bs: { ?sBS a locah:ArchivalResource } }
{ GRAPH ne: { ?sNE a locah:ArchivalResource } }
}