SPARQL/修饰符
SELECT ... WHERE { .. } 有 4 个可选修饰符。有关介绍,请参见SELECT 章节。
五个修饰符是 GROUP BY ...、HAVING ...、ORDER BY ...、LIMIT ... 和 OFFSET ...。
让我们考虑一下巴赫的孩子列表,其中还列出了他们的母亲
SELECT ?mother ?motherLabel ?child ?childLabel
WHERE
{
?child wdt:P22 wd:Q1339.# ?child has father Bach
?child wdt:P25 ?mother.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
让我们按母亲对这个列表进行分组。
SELECT ?mother ?motherLabel (COUNT(?child) AS ?children)
(GROUP_CONCAT(DISTINCT ?childLabel; SEPARATOR=", ") AS ?names)
WHERE
{
?child wdt:P22 wd:Q1339.# ?child has father Bach
?child wdt:P25 ?mother.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en".
?mother rdfs:label ?motherLabel.
?child rdfs:label ?childLabel.
}
}
GROUP BY ?mother ?motherLabel
我们对 ?mother 和 ?motherLabel 两个变量都使用 GROUP BY,因为如果省略标签,最终会得到“错误的聚合”错误。
首先,我们添加了 (COUNT(?child) AS ?children) 来计算孩子的数量。COUNT 是 聚合函数 MIN、MAX、SUM、AVG、COUNT 或 SAMPLE 之一。
首先要注意的是它计算了变量 ?child。还要注意语法是 (COUNT(?var1) AS ?var2)。
作为第二条信息,我们使用 (GROUP_CONCAT(DISTINCT ?var1; SEPARATOR=", ") AS ?var2) 添加了每个母亲的孩子的组合列表。
在使用 GROUP_CONCAT 和标签时,所有标签都应在 SERVICE 中明确定义。
HAVING 始终与 GROUP BY 结合使用
SELECT ?mother ?motherLabel (COUNT(?child) AS ?children)
(GROUP_CONCAT(DISTINCT ?childLabel; SEPARATOR=", ") AS ?names)
WHERE
{
?child wdt:P22 wd:Q1339.# ?child has father Bach
?child wdt:P25 ?mother.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en".
?mother rdfs:label ?motherLabel.
?child rdfs:label ?childLabel.
}
}
GROUP BY ?mother ?motherLabel
HAVING (COUNT(?child)>7)
HAVING 将过滤掉不满足指定条件的组。在这种情况下,只显示一位母亲,她有 13 个孩子。
由于 COUNT(?child) 与变量 ?children 绑定,因此 HAVING 子句也可以写成 HAVING (?children>7)。
HAVING 子句对于查找重复项可能很有用,例如 HAVING (COUNT(?var)>1)。
ORDER BY something 按 something 对结果进行排序。something 可以是任何表达式或变量。此表达式也可以用 ASC() 或 DESC() 包裹以指定排序顺序(ascending 或 descending)。(如果未指定任何一个,则默认值为升序排序,因此 ASC(something) 等效于 something。)
SELECT ?mother ?motherLabel ?child ?childLabel
WHERE
{
?child wdt:P22 wd:Q1339.# ?child has father Bach
?child wdt:P25 ?mother.
SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
}
ORDER BY DESC(?motherLabel) ?childLabel
LIMIT count 将结果列表截断为 count 个结果,其中 count 是任何自然数。例如,LIMIT 10 将查询限制为十个结果。LIMIT 1 仅返回单个结果。
这对于获取前 10 个结果或仅获取 10 个随机结果以查看数据的外观可能很有用。
OFFSET count 可用于跳过前几个结果。OFFSET 100 LIMIT 10 返回第 101-110 条记录。