如何在SPARQL查询中筛选仅含单一包装类型的乐高主题
修改SPARQL查询以筛选仅含单一包装类型的乐高主题
要实现只保留仅有一种包装类型的乐高主题,你需要先筛选出那些包装类型数量为1的主题,再基于这些主题统计对应的套装信息。可以通过以下方式修改查询:
WITH { SELECT ?theme WHERE { ?Lego_set rdf:type wd:Q58780257 . ?Lego_set sch:audienceType ?audience . ?Lego_set ex:has_package_information ?package_info . ?audience ex:belongs_to_theme ?theme . ?package_info ex:has_packaging_type ?package_type . } GROUP BY ?theme HAVING (COUNT(DISTINCT ?package_type) = 1) } AS %single_package_themes SELECT ?theme ?package_type (COUNT(?Lego_set) AS ?amount_of_lego_sets) WHERE { INCLUDE %single_package_themes ?Lego_set rdf:type wd:Q58780257 . ?Lego_set sch:audienceType ?audience . ?Lego_set ex:has_package_information ?package_info . ?audience ex:belongs_to_theme ?theme . ?package_info ex:has_packaging_type ?package_type . } GROUP BY ?theme ?package_type ORDER BY ?theme
关键调整说明:
- 新增
WITH子查询块:先按?theme分组,用COUNT(DISTINCT ?package_type)统计每个主题下的不同包装类型数量,通过HAVING子句筛选出数量等于1的主题,将这些主题存入临时集合%single_package_themes。 - 主查询通过
INCLUDE %single_package_themes只处理符合条件的主题,自动排除拥有多种包装类型的主题。 - 修正统计逻辑:将原查询的
count(?theme)改为COUNT(?Lego_set),更准确地统计每个主题对应包装类型下的乐高套装数量。
内容的提问来源于stack exchange,提问作者Nijenhof
相关产品推荐
相关产品推荐

