2014-08-28 66 views
0

我想使用XQuery 3.0創建一個摘要來顯示obj具有的每種類型的多少部分。我有以下XML代碼:如何根據屬性值來計算子節點?

<root> 
    <obj> 
     <name>Foo1</name> 
     <stuff> 
      <part type = "a"/> 
      <part type = "a"/> 
      <part type = "b"/> 
      <part type = "d"/> 
      <part type = "d"/> 
     </stuff> 
    </obj> 
    <obj> 
     <name>Foo2</name> 
     <stuff> 
      <part type = "a"/> 
      <part type = "c"/> 
      <part type = "c"/> 
     </stuff> 
    </obj> 
    <obj> 
     <name>Foo3</name> 
     <stuff> 
      <part type = "a"/> 
      <part type = "a"/> 
      <part type = "a"/> 
      <part type = "b"/> 
      <part type = "b"/> 
      <part type = "c"/> 
      <part type = "d"/> 
     </stuff> 
    </obj> 
</root> 

而且我想顯示的結果類似於下列方式之一:

 OR 
Foo1 | Foo1 
a 2  | a 2 
b 1  | b 1 
d 2  | c 0 
     | d 2 
     | 
Foo2 | Foo2 
a 1  | a 1 
c 2  | b 0 
     | c 2 
     | d 0 
     | 
Foo3 | Foo3 
a 3  | a 3 
b 2  | b 2 
c 1  | c 1 
d 1  | d 1 
     | 

回答

2

GROUP BY應該很好的工作在這裏:

for $obj in //obj 
return 
    <result> 
    {$obj/name} 
    { 
    for $part in $obj//part 
      group by $type := $part/@type 
      return <part type="{$type}">{count($part)}</part> 
    } 
    </result> 
相關問題