2012-05-03 22 views
8

鑑於這種非常簡單的模型:如何做一個COUNT在SPARQL

@prefix :  <http://example.org/tags#> . 
@prefix owl:  <http://www.w3.org/2002/07/owl#> . 
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . 
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . 
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> . 

:tag rdf:type rdf:Property . 

:item1 
     rdf:type owl:Thing ; 
     :tag "a"^^xsd:string . 

:item2 
     rdf:type owl:Thing ; 
     :tag "a"^^xsd:string , "b"^^xsd:string . 

:item3 
     rdf:type owl:Thing ; 
     :tag "a"^^xsd:string , "b"^^xsd:string , "c"^^xsd:string . 

我想獲得的物品的清單和標籤的數量,每個有:

item tagCount 
===== ======== 
item1 1 
item2 2 
item3 3 

這裏是我的查詢:

SELECT ?item (count(?tag) as ?tagcount) 
WHERE { 
    ?item :tag ?tag 
} 

但是它返回:

item tagCount 
===== ======== 
     6 

從我讀過的,這應該工作。我正在使用耶拿2.6.4

+1

'COUNT'不是SPARQL 1.0規範的一部分,它是在1.1中添加的。儘管如此,一些實現支持它。只是說。 –

+0

Upvoted清晰表達的問題和正確的格式! – cygri

回答

6

我還沒有試過這個,但是嘗試在查詢的末尾添加GROUP BY ?item。我認爲沒有GROUP BY它只是計算總行數。

+0

是的,它計算總行數。這與SQL在這種情況下所做的完全相同。但是,我不知道'item'會發生什麼情況。 –

3

對於綁定到出現在結果中,你確實需要通過關鍵字可以使用組所以這成爲

選擇項目(計數(標籤)作爲tagcount?) WHERE { 項目:?標籤?標籤 }組通過?項目

如果你要計算在查詢的中間有東西,你會做到以下幾點,注意,您必須如何把內選擇查詢到自己的塊{}

SELECT * { 
    ?item a owl:Thing . 

    { 
     SELECT ?item (count(?tag) as ?tagcount) 
     WHERE { 
      ?item :tag ?tag 
     } group by ?item 
    } 
} 
0

子選擇@ user2316243是不必要的,因此以下查詢是等效的:

SELECT ?item (count(?tag) as ?tagcount) 
WHERE { 
    ?item a owl:Thing . 
    ?item :tag ?tag . 
} GROUP BY ?item