2017-08-30 127 views
0

給定此數據,其中每個人可以選擇具有「智能」謂詞,並且每個部門可能有零個或多個人,我需要查找僅包含聰明的人。結果應該只包括部門1和2.理想情況下,結果還應包括每個部門的「智能」對象。謝謝!SPARQL:查找所有子對象與條件匹配的對象

person:A p:type 'p' ; 
      p:smart 'yes' . 
person:B p:type 'p' ; 
      p:smart 'maybe' . 
person:C p:type 'p' . 

department:1 p:type 'd' ; 
       p:has person:A, person:B . 
department:2 p:type 'd' ; 
       p:has person:B . 
department:3 p:type 'd' ; 
       p:has person:B, person:C . 
department:4 p:type 'd' . 

回答

3

我有一種感覺,我已經回答過類似的事情,但無論如何,有一個合理的很好的方式做到這一點:

select ?dept 
    (count(?person) as ?pc) (count(?smart) as ?sc) 
    (group_concat(?smart; separator=',') as ?smarts) 
{ 
    ?dept p:has ?person . 
    optional { ?person p:smart ?smart } 
} 
group by ?dept 
having (?pc = ?sc) 

那就是:找部門,人員和(其中可用)智能價值。對於每個部門查找人數與智能值數量相匹配的人員。

------------------------------------------------------------- 
| dept        | pc | sc | smarts  | 
============================================================= 
| <http://example.com/department#2> | 1 | 1 | "maybe"  | 
| <http://example.com/department#1> | 2 | 2 | "yes,maybe" | 
------------------------------------------------------------- 

當你想爲每個對象的結果,滿足某種條件,group by/having往往是最乾淨的答案(因爲你可以分離出從過濾匹配)。

+0

我真的很喜歡這個解決方案!我想知道哪一個通常更快,但也許沒有太大的差別。當我有時間的時候,我會嘗試一些小的「基準」。乾杯 – AKSW

+0

我應該指出,這個解決方案依賴於每個人最多帶來一個智能價值。要解決更復雜的案例並不難,但它們不太漂亮(聚合/有條件變得更長)。至於速度,我懷疑大多數理智的商店沒有太大的區別(即他們按照正常的順序進行過濾器連接),但是測試會很有趣。 – user205512

+0

至少現在你的答案是被接受的答案,所以也許有一些優點。知道哪些是有趣的:D – AKSW

2

喜歡的東西雙重否定可能的工作:

SELECT DISTINCT ?dept WHERE { 
    ?dept p:has ?person . 
    FILTER NOT EXISTS { 
    ?dept p:has ?person1 . 
    FILTER NOT EXISTS { 
    ?person1 p:smart ?smartVal 
    } 
    } 
} 

結果:

+---------------+ 
|  dept  | 
+---------------+ 
| department:1 | 
| department:2 | 
+---------------+ 

有了值:

SELECT ?dept (GROUP_CONCAT(DISTINCT ?smart;separator=";") as ?smartValues) WHERE { 
    ?dept p:has ?person . 
    ?person p:smart ?smart 
    FILTER NOT EXISTS { 
    ?dept p:has ?person1 . 
    FILTER NOT EXISTS { 
    ?person1 p:smart ?smartVal 
    } 
    } 
} 
GROUP BY ?dept 

結果:

+---------------+-------------+ 
|  dept  | smartValues | 
+---------------+-------------+ 
| department:1 | maybe;yes | 
| department:2 | maybe  | 
+---------------+-------------+ 
相關問題