我已经在我的第二个简单查询工作了几天。我应该做的就是声明一个全局变量($ crime),指向XML文件中的所有犯罪元素,并使用FLWOR查询迭代day元素的每个唯一值,以便我可以看到哪些日期最多犯罪(应该是星期六,星期一,然后星期日顺序)。我也一直收到这个错误:
查询意外结束;变量" $ crime"。
代码:
xquery version "1.0";
delare variable $crimes := doc('dc_crime.xml')//crime;
(:
Query to display total number of crimes by
day of the week
:)
<results>{
for $day in distinct-values(doc('dc_crime.xml')/$day
let $crimes := sum($crimes/($day/$crimes))
order by $day descending order
return
<crime day="{$day}" crimes="{$count}">{$crimes}</crime>
}</results>
XML示例:
<crime id="13402531">
<dateTime>2013-08-31T20:27:00</dateTime>
<month>8-Aug</month>
<day>7-Sat</day>
<offense>THEFT/OTHER</offense>
<method>OTHERS</method>
<ward>3</ward>
</crime>
<crime id="13402533">
<dateTime>2013-08-28T17:06:00</dateTime>
<month>8-Aug</month>
<day>4-Wed</day>
<offense>THEFT F/AUTO</offense>
<method>OTHERS</method>
<ward>1</ward>
</crime>
<crime id="13402547">
<dateTime>2013-08-31T20:05:00</dateTime>
<month>8-Aug</month>
<day>7-Sat</day>
<offense>THEFT F/AUTO</offense>
<method>OTHERS</method>
<ward>6</ward>
</crime>
<crime id="13402704">
<dateTime>2013-08-03T17:29:00</dateTime>
<month>8-Aug</month>
<day>7-Sat</day>
<offense>THEFT/OTHER</offense>
<method>OTHERS</method>
<ward>2</ward>
</crime>
</crimes>
请帮忙......
答案 0 :(得分:1)
这是一个可能的XQuery: 1。使用全局变量和 2。计算每天的犯罪数量,并按照该数字的顺序返回结果,降序:
declare variable $crimes := doc('dc_crime.xml')//crime;
<results>{
for $day in distinct-values(doc('dc_crime.xml')//day)
(: get all crimes that happen at current day of week :)
let $details := $crimes[day=$day]
(: count number crimes that happen at current day of week :)
let $count := count($details)
(: return the result in the order of $count, descending :)
order by $count descending
return
<crime day="{$day}" crimes="{$count}">{$details}</crime>
}</results>
<强> xpathtester demo
强>
输出
<results>
<crime crimes="3" day="7-Sat">
<crime id="13402531">
<dateTime>2013-08-31T20:27:00</dateTime>
<month>8-Aug</month>
<day>7-Sat</day>
<offense>THEFT/OTHER</offense>
<method>OTHERS</method>
<ward>3</ward>
</crime>
<crime id="13402547">
<dateTime>2013-08-31T20:05:00</dateTime>
<month>8-Aug</month>
<day>7-Sat</day>
<offense>THEFT F/AUTO</offense>
<method>OTHERS</method>
<ward>6</ward>
</crime>
<crime id="13402704">
<dateTime>2013-08-03T17:29:00</dateTime>
<month>8-Aug</month>
<day>7-Sat</day>
<offense>THEFT/OTHER</offense>
<method>OTHERS</method>
<ward>2</ward>
</crime>
</crime>
<crime crimes="1" day="4-Wed">
<crime id="13402533">
<dateTime>2013-08-28T17:06:00</dateTime>
<month>8-Aug</month>
<day>4-Wed</day>
<offense>THEFT F/AUTO</offense>
<method>OTHERS</method>
<ward>1</ward>
</crime>
</crime>
</results>