2015-04-01 63 views
0

我一直在尋找過去的一個小時如何找到一個元素分組的最大值,但沒有成功。找到xml中每個元素的最大屬性?

我想報告的pid和uid和每用戶

這裏的最高playcount播放列表的playcount是我的xml文件:

<!DOCTYPE users SYSTEM "users.dtd"> 
<users> 
<user uid = "u1" dob = "06/03/94" email = "[email protected]"> 
    <surname> Doe</surname> 
    <givennames> Jon </givennames> 
    <follows who = "u1 u2"/> 
    <playlists> 
     <playlist pid = "p1" created ="12/03/11" playcount = "5" /> 
    </playlists> 
    </user> 

    <user uid = "u2" dob = "06/03/95" email = "[email protected]"> 
    <surname> Dod</surname> 
    <givennames> Jane </givennames> 
    <follows who = "u1 u3"/> 
    </user> 

    <user uid = "u3" dob = "06/04/95" email = "[email protected]"> 
    <surname> ron</surname> 
    <givennames> dave </givennames> 
    <follows who = "u1 u2"/> 
    <playlists> 
     <playlist pid = "p3" created ="12/02/09" playcount = "9"/> 
     <playlist pid = "p9" created = "11/11/11" playcount = "11"/> 
    </playlists> 
    </user> 

    <user uid = "u4" dob = "06/04/99" email = "[email protected]"> 
    <surname> dun</surname> 
    <givennames> jeff</givennames> 
    <follows who = "u1 u2 u3"/> 
    <playlists> 
     <playlist pid = "p4" created ="12/02/09" playcount = "3"/> 
     <playlist pid = "p6" created ="12/02/09" playcount = "55"/> 
    </playlists> 
    </user> 

</users> 

我試着做

for $user in doc("users.xml")/users/user 
where $users/playlists/playlist/@playcount = max($users/playlists/playlist/@playcount) 
    return $user 

但它不工作..沒有我已經嘗試過工作......它要麼返回我每個用戶的最大playcount(這是我得到的最好的,因爲這是有點什麼我的想法WA NT出此查詢),或者我讓每一個播放列表

我需要一個查詢,輸出:

<favorites> 
    <user uid = "u1" pid = "p1" playcount = "5"/> 
    <user uid = "u2" /> 
    <user uid = "u3" pid = "p9" playcount = "11"/> 
    <user uid = "u4" pid = "p6" playcount = "55"/> 
</favorites> 

播放列表是一個可選的元素,所以如果用戶沒有一個播放列表,然後只報告的UID。 。

有幫助嗎?真的在我的智慧在這裏結束,因爲它似乎很難找到查找使用按元素分組的最大功能查詢的一個例子..

+0

XQuery 1.0或XQuery 3.0?版本3.0有一個「group by」結構。 – 2015-04-01 10:08:50

回答

2

我想你需要分支的情況下,還自定義輸出格式。這裏是我的xquery:

let $users := doc("users.xml")/users/user 
for $user in $users 
let $maxCount := max($user/playlists/playlist/@playcount) 
let $maxPlaylist := $user/playlists/playlist[@playcount = $maxCount] 
return if (count($maxPlaylist) > 0) 
then <user uid="{$user/@uid}" pid = "{$maxPlaylist/@pid}" playcount = "{$maxPlaylist/@playcount}"/> 
else <user uid="{$user/@uid}"/>