2013-12-10 78 views
3

我想指望類似「itemid_ref」,讓每個項目的數量REF在此:GROUP BY和XQuery中

<?xml version="1.0" encoding="utf-8"?> 
<electrystore> 
    <itembill> 
    <itembill_id>1</itembill_id> 
    <itemid_ref>2</itemid_ref> 
    <billid_ref>2</billid_ref> 
    <price>20000</price> 
    </itembill> 
    <itembill> 
    <itembill_id>2</itembill_id> 
    <itemid_ref>3</itemid_ref> 
    <billid_ref>3</billid_ref> 
    <price>250000</price> 
    </itembill> 
    <itembill> 
    <itembill_id>3</itembill_id> 
    <itemid_ref>3</itemid_ref> 
    <billid_ref>3</billid_ref> 
    <price>30000</price> 
    </itembill> 
    <itembill> 
    <itembill_id>4</itembill_id> 
    <itemid_ref>1</itemid_ref> 
    <billid_ref>2</billid_ref> 
    <price>140000</price> 
    </itembill> 
    <itembill> 
    <itembill_id>5</itembill_id> 
    <itemid_ref>2</itemid_ref> 
    <billid_ref>1</billid_ref> 
    <price>10000</price> 
    </itembill> 
</electrystore> 

我想從XQuery的輸出是這樣的:

<?xml version="1.0" encoding="UTF-8"?> 
<results> 
<result> 
    <itemid_ref> 
     2 
    </itemid_ref> 
    <numberOfitemes>2</numberOfitemes> 
</result> 
<result> 
    <itemid_ref> 
     3 
    </itemid_ref> 
    <numberOfitemes>2</numberOfitemes> 
</result> 
<result> 
    <itemid_ref> 
     1 
    </itemid_ref> 
    <numberOfitemes>1</numberOfitemes> 
</result> 

我該怎麼做?

回答

3

XQuery 1.0中沒有group by,但通常情況下,只要數據集不是太大,通常可以使用distinct-values

for $itemid_ref in distinct-values(/electrystore/itembill/itemid_ref) 
let $count := count(/electrystore/itembill[itemid_ref = $itemid_ref]) 
return element result { 
    element itemid_ref { $itemid_ref }, 
    element numberOfitemes { $count } 
} 

要在大型數據集上執行,您可能需要查看XQuery處理器中允許訪問索引的擴展。

在XQuery中3.0這是一個有點簡單:

for $itembill in /electrystore/itembill 
let $itemid_ref := $itembill/itemid_ref 
group by $itemid_ref 
return element result { 
    element itemid_ref { $itemid_ref }, 
    element numberOfitemes { count($itembill) } 
} 
+0

是它的工作原理:) 非常感謝你和關於XQuery 3.0的說明 – user3076314