W3C

XQuery 3.0 Use Cases

W3C Working Group Note 08 April 2014

This version:
http://www.w3.org/TR/2014/NOTE-xquery-30-use-cases-20140408/
Latest version:
http://www.w3.org/TR/xquery-30-use-cases/
Previous versions:
http://www.w3.org/TR/2013/WD-xquery-30-use-cases-20130108/, http://www.w3.org/TR/2012/WD-xquery-30-use-cases-20120327/, http://www.w3.org/TR/2010/WD-xquery-30-use-cases-20101214/, http://www.w3.org/TR/2008/WD-xquery-11-use-cases-20081203/, http://www.w3.org/TR/2008/WD-xquery-11-use-cases-20080711/
Editors:
Jonathan Robie, EMC Corporation
Tim Kraska, FLWOR Foundation

This document is also available in these non-normative formats: XML.


Abstract

This document specifies usage scenarios for XML Query (XQuery) 3.0.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is a Working Group Note as described in the Process Document. It was developed by the W3C XML Query Working Group, which is part of the XML Activity.

This document provides a number of use cases designed to evaluate XQuery 3.0, the requirements for which are specified in [XQuery 3.0 Requirements].

This document incorporates changes made against the previous publication of the Working Draft. Changes to this document since the previous publication of the Working Draft are detailed in B Change Log.

Please report errors in this document using W3C's public Bugzilla system (instructions can be found at http://www.w3.org/XML/2005/04/qt-bugzilla). If access to that system is not feasible, you may send your comments to the W3C XSLT/XPath/XQuery public comments mailing list, [email protected]. It will be very helpful if you include the string “[XQuery30UC]” in the subject line of your report, whether made in Bugzilla or in email. Please use multiple Bugzilla entries (or, if necessary, multiple email messages) if you have more than one comment to make. Archives of the comments and responses are available at http://lists.w3.org/Archives/Public/public-qt-comments/.

Publication as a Working Group Note does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1 Use Cases for XML Query 3.0
2 Shopping Scenario: Schema and Data
    2.1 Schema
    2.2 Sample Data
3 Use Case "Group By" - Queries which require value-based grouping
    3.1 Schema and Sample Data
        3.1.1 Schema Q7-Q8
        3.1.2 Sample Data Q7-Q8
    3.2 Queries and Results
        3.2.1 Q1
        3.2.2 Q2
        3.2.3 Q3
        3.2.4 Q4
        3.2.5 Q5
        3.2.6 Q6
        3.2.7 Q7
        3.2.8 Q8
4 Use Case "Windowing" - Queries which require windowing
    4.1 Schema and Sample Data
        4.1.1 XML Schema for Q1
        4.1.2 Sample Data for Q1
        4.1.3 XML Schema for Q2
        4.1.4 Sample Data for Q2
        4.1.5 XML Schema for Q3
        4.1.6 Sample Data for Q3
        4.1.7 XML Schema for Q4-Q6
        4.1.8 Sample Data for Q4-Q6
        4.1.9 XML Schema for Q7-Q13
        4.1.10 Sample Data for Q7-Q13
        4.1.11 XML Schema for Q14-Q16
        4.1.12 Sample Data for Q14-Q16
        4.1.13 XML Schema for Q17-Q19
        4.1.14 Sample Data for Q17-Q19
    4.2 Queries and Results
        4.2.1 Q1
        4.2.2 Q2
        4.2.3 Q3
        4.2.4 Q4
        4.2.5 Q5
        4.2.6 Q6
        4.2.7 Q7
        4.2.8 Q8
        4.2.9 Q9
        4.2.10 Q10
        4.2.11 Q11
        4.2.12 Q12
        4.2.13 Q13
        4.2.14 Q14
        4.2.15 Q15
        4.2.16 Q16
        4.2.17 Q17
        4.2.18 Q18
        4.2.19 Q19
5 Use Case "Count" - Queries which require output numbering
    5.1 Schema and Sample Data
    5.2 Queries and Results
        5.2.1 Q1
        5.2.2 Q2
        5.2.3 Q3
6 Use Case "Outer For" - Queries which require outer joins
    6.1 Schema and Sample Data
    6.2 Queries and Results
        6.2.1 Q1
        6.2.2 Q2
7 Use Case "Try-Catch" - Queries which require to recover from errors
    7.1 Sample Data
    7.2 Queries and Results
        7.2.1 Q1
        7.2.2 Q2
        7.2.3 Q3

Appendices

A Acknowledgements (Non-Normative)
B Change Log (Non-Normative)
    B.1 30 Mar 2011
    B.2 30 January 2008
    B.3 17 November 2008
C References (Non-Normative)


1 Use Cases for XML Query 3.0

The use cases listed below were created by the XML Query Working Group to illustrate important applications for the new features in XQuery 3.0. Each use case is focused on a specific application area, and contains a XML Schema and example input data. Each use case specifies a set of queries that might be applied to the input data, and the expected results for each query. Since the English description of each query is concise, the expected results form an important part of the definition of each query, specifying the expected output format.

Most of the listed use cases are based on a simple shopping scenario described in section Schema and Data. Use cases which require special data have a seperate subsection describing the XML Schema and input data. All use cases assume that input is provided in the form of one or more documents with specific names. For instance, the products in a document may be accessed with expressions like this:

doc("products.xml")//product

Several implementors have asked us to make the queries from these use cases available in a separate file in order to make it easier for them to test their parsers. These queries may be found in [Use Case Sample Queries]

To make output more readable, the output of queries has been formatted using whitespace which may not be returned by a query processor. This whitespace should not be considered normative for the correctness of results.

These queries were tested with a dynamic implementation of XQuery. Some queries may require additional type declarations to be used with an implementation that implements the Static Typing feature.

2 Shopping Scenario: Schema and Data

If not stated otherwise all use cases in this document are based on a simplified shopping scenario containing three documents. The first document, products.xml, contains a list of products, whereas stores.xml includes a list of stores, and sales-records.xml contains the list of sales.

2.1 Schema

The document product.xml uses the following XML Schema:


    
        
            
                
                    
                        
                            
                            
                            
                            
                        
                    
                
            
        
    

The sales-records.xml document follows this XML Schema:


    
        
            
                
                    
                        
                            
                            
                            
                        
                    
                
            
        
    

The stores.xml document is valid to this XML Schema:


    
        
            
                
                    
                        
                            
                            
                        
                    
                
            
        
    

2.2 Sample Data

The content of the document products.xml is:


  
    broiler
    kitchen
    100
    70
  
  
    toaster
    kitchen
    30
    10
  
  
    blender
    kitchen
    50
    25
  
  
    socks
    clothes
    5
    2
  
  
    shirt
    clothes
    10
    3
  

The content of sales-records.xml is:


  
    broiler
    1
    20
  
  
    toaster
    2
    100
  
  
    toaster
    2
    50
  
  
    toaster
    3
    50
  
  
    blender
    3
    100
  
  
    blender
    3
    150
  
  
    socks
    1
    500
  
  
    socks
    2
    10
  
  
    shirt
    3
    10
  

The content of stores.xml is:


  
    1
    CA
  
  
    2
    CA
  
  
    3
    MA
  
  
    4
    WA
  

3 Use Case "Group By" - Queries which require value-based grouping

This use case contains several sample queries in which value based grouping is needed.

3.1 Schema and Sample Data

Queries 1-6 are based on a simplified shop scenario with products, sales records and different shop locations. The schema and data can be found in section Schema and Data. Queries 7 and 8 are based on a bibliography document shown below:

3.1.1 Schema Q7-Q8

Q7 and Q8 use an input document named "books.xml", with the following XML Schema:


    
        
            
                
                    
                        
                            
                            
                        
                    
                
            
        
    

3.1.2 Sample Data Q7-Q8

Here are the contents of books.xml:


  
    Jim Melton
    Alan Simon
    SQL:1999
  
  
    Jim Melton
    Advanced SQL:1999
  
  
    Alan Simon
    Strategic Database Technology
  
  
    Jim Melton
    Andrew Eisenberg
    Understanding SQL and Java Together
  
  
    Jim Melton
    Stephen Buxton
    Querying XML
  

3.2 Queries and Results

3.2.1 Q1

Group sales by product, list name and total quantity of each product.

Solution in XQuery:

{
  for $sales in doc("sales-records.xml")/*/record
  let $pname := $sales/product-name
  group by $pname
  order by $pname
  return
    {
      sum($sales/qty)
    }
} 

Expected Result:


  250
  20
  10
  510
  200

3.2.2 Q2

Group sales by state (a property of the store) and category (a property of the product). Order groups by the grouping keys. For each group, show the total quantity sold.

Solution in XQuery:

{
  for $sales in doc("sales-records.xml")/*/record
  let $state := doc("stores.xml")/*/store[store-number = $sales/store-number]/state
  let $category := doc("products.xml")/*/product[name = $sales/product-name]/category
  group by $state, $category
  order by $state, $category
  return
    
      {$state}
      {$category}
      {sum($sales/qty)}
    
}

Expected Result:


  
    CA
    clothes
    510
  
  
    CA
    kitchen
    170
  
  
    MA
    clothes
    10
  
  
    MA
    kitchen
    300
  

3.2.3 Q3

Group sales by state (a property of the store) and category (a property of the product). Order groups by the grouping keys. For each group, show the total revenue (defined as sales/qty * product/price).

Solution in XQuery:

{
  for $sales in doc("sales-records.xml")/*/record
  let $state := doc("stores.xml")/*/store[store-number = $sales/store-number]/state,
    $product := doc("products.xml")/*/product[name = $sales/product-name],
    $category := $product/category,
    $revenue := $sales/qty * $product/price
  group by $state, $category
  order by $state, $category
  return
    
      {$state}
      {$category}
      {sum($revenue)}
    
}

Expected Result:


  
    CA
    clothes
    2550
  
  
    CA
    kitchen
    6500
  
  
    MA
    clothes
    100
  
  
    MA
    kitchen
    14000
  

3.2.4 Q4

Combine the input documents into a three-level hierarchy based on state, category, and product. At the product level, show the total quantity sold of each product. List items alphabetically at each level of the hierarchy.

Solution in XQuery:

{
  for $store in doc("stores.xml")/*/store
  let $state := $store/state
  group by $state
  order by $state
  return
    {
      for $product in doc("products.xml")/*/product
      let $category := $product/category
      group by $category
      order by $category
      return
        {
          for $sales in doc("sales-records.xml")/*/record[store-number = $store/store-number
            and product-name = $product/name]
          let $pname := $sales/product-name
          group by $pname
          order by $pname
          return
            
          }
    }
}

Expected Result:


  
    
      
    
    
      
      
    
  
  
    
      
    
    
      
      
    
  

3.2.5 Q5

List all stores in ascending order by store number. For each store, list the products sold in that store, in descending order by quantity sold. Illustrates ordering among and within groups.

Solution in XQuery:

{
  for $sales in doc("sales-records.xml")/*/record
  let $storeno := $sales/store-number
  group by $storeno
  order by $storeno
  return
    {
      for $s in $sales
      order by xs:int($s/qty) descending
      return
        
    }
}

Expected Result:


  
    
    
  
  
    
    
    
  
  
    
    
    
    
  

3.2.6 Q6

List all stores whose total profit is greater than 100, in descending order by total profit. Note: total profit for a store is the sum over all sales in that store, of the quantity sold times the difference between price and cost for the item sold. Illustrates cross-document computation, filtering of groups, ordering by a non-grouping key.

Solution in XQuery:

{
  for $sales in doc("sales-records.xml")/*/record
  let $storeno := $sales/store-number,
    $product := doc("products.xml")/*/product[name = $sales/product-name],
    $prd := $product,
    $profit := $sales/qty * ($prd/price - $prd/cost)
  group by $storeno
  let $total-store-profit := sum($profit)
  where $total-store-profit > 100
  order by $total-store-profit descending
  return
    
 }

Expected Result:


  
  
  

3.2.7 Q7

Group books by author. Create a group for each individual author. A book with multiple authors should appear in the groups for each of its authors. Alphabetize the authors and the book titles within each author group.

Solution in XQuery:

{
  for $book in doc("books.xml")/*/book
  for $author in $book/author
  group by $author
  order by $author
  return
  {
    for $b in $book
    order by $b/title
    return
       {fn:data($b/title)} 
  }
}

Expected Result:


  
    SQL:1999
    Strategic Database Technology
  
  
    Understanding SQL and Java Together
  
  
    Advanced SQL:1999
    Querying XML
    SQL:1999
    Understanding SQL and Java Together
  
  
    Querying XML
  

3.2.8 Q8

Group books by author. Create a group for each distinct ordered list of authors. Each book should be grouped with other books that have the same ordered list of authors. Alphabetize the book titles within each group.

Solution in XQuery:

{
  for $book in doc("books.xml")/*/book
  let $author-list := fn:string-join($book/author, ', ')
  group by $author-list
  order by $author-list
  return
    {
      for $b in $book
      order by $b/title
      return
         {fn:data($b/title)} 
    }
}

Expected Result:


  
    Strategic Database Technology
  
  
    Advanced SQL:1999
  
  
    SQL:1999
  
  
    Understanding SQL and Java Together
  
  
    Querying XML
  

4 Use Case "Windowing" - Queries which require windowing

This use case covers queries that require windowing or positional grouping, which can be seen as a special form of windowing. Windowing means that the queries require selecting subsequences based on certain characterisics of an underlying sequence.

4.1 Schema and Sample Data

Windowing is required in various scenarios from formatting up to streaming applications. The listed queries try to cover different scenarios and require therefore also various types of input data. The following sections describe for every query the used data and the according schema.

4.1.1 XML Schema for Q1

Q1 uses an input document named arrange_rows.xml, with the following XML Schema arrange_rows.xsd:


    
        
            
                
            
        
    

4.1.2 Sample Data for Q1

The content of arrange_rows.xml is:


  Green
  Pink
  Lilac
  Turquoise
  Peach
  Opal
  Champagne

4.1.3 XML Schema for Q2

Q2 uses an input document named head_para.xml, with the following XML Schema named head_para.xsd:


    
        
            
                
                    
                    
                
            
        
    

4.1.4 Sample Data for Q2

The content of head_para.xml is:


  

heading1

para1

para2

heading2

para3

para4

para5

4.1.5 XML Schema for Q3

Q3 uses an input document named term_def_list.xml, with the following XML Schema named term_def_list.xsd:


    
        
            
                
                    
                    
                
            
        
    

4.1.6 Sample Data for Q3

The content of term_def_list.xml is:


  
XML
Extensible Markup Language
XSLT
XSL Transformations
A language for transforming XML
A specification produced by W3C

4.1.7 XML Schema for Q4-Q6

Q4 - Q6 use an input document named temp_events.xml, with the following XML Schema named temp_events.xsd:


    
        
            
                
                    
                        
                        
                    
                
            
        
    

4.1.8 Sample Data for Q4-Q6

The content of temp_events.xml is:


  
  
  
  
  
  
  

4.1.9 XML Schema for Q7-Q13

Q7 - Q13 use an input document named person_events.xml, with the following XML Schema named person_events.xsd:


    
        
            
                
                    
                        
                            
                            
                        
                        
                    
                
            
        
    

4.1.10 Sample Data for Q7-Q13

The content of person_events.xml is:


  
  
    Anton
    in
  
  
    Barbara
    in
  
  
    Clara
    in
  
  
    Clara
    out
  
  
    Barbara
    out
  
  
    Anton
    out
  
  
  
  
    Anton
    in
  
  
    Clara
    in
  
  
    Clara
    out
  
  
    Clara
    in
  
  
    Clara
    out
  
    
    Clara
    in
  
  
    Clara
    out
  
  
    Clara
    in
  
  
    Anton
    out
  
  
    Clara
    out
  
  

4.1.11 XML Schema for Q14-Q16

Q14 - Q16 use as input document a slightly modified RSS document named rss.xml. It mainly differs from RSS 2.0 in the way dates are expressed in the data. The XML Schema, rss.xsd, is as follows:


    
        
            
                
                    
                        
                            
                            
                            
                            
                            
                        
                    
                
            
        
    
    
        
            
                
                
                
                
            
        
    

4.1.12 Sample Data for Q14-Q16

The content of rss.xml is:


  
    DBIS RSS
    http://www.dbis.ethz.ch
    The windowing dummy RSS.
    en-us
    
      Why use cases are important Part 1.
      Workshop
      [email protected]
      2003-06-03T09:00:00
    
    
      Why use cases are important Part 2.
      Workshop
      [email protected]
      2003-06-03T09:00:00
    
    
      Why use cases are important Part 3.
      Workshop
      [email protected]
      2003-06-03T10:00:00
    
    
      Extending XQuery with Window Functions
      Talk
      [email protected]
      2003-06-03T11:00:00
    
    
      XQueryP: A new programming language is born
      Talk
      [email protected]
      2003-06-03T12:00:00
    
    
      Why use cases are annoying to write.
      Talk
      [email protected]
      2003-06-04T10:00:00
    
  

4.1.13 XML Schema for Q17-Q19

Q17-Q19 use an input document named cxml.xml. The structure of this document is inspired by the Commerce XML Resource standard (cXML). The document contains a sequence of events, where an event corresponds to a simplified message of the cXML standard or an timeclock event. The XML Schema with the file-name cxml.xsd is as follows:


    
        
            
                
                    
                    
                    
                    
                
            
        
    
    
        
    
    
        
            
                
                    
                    
                    
                
            
        
        
        
        
        
        
        
    
    
        
        
        
        
    
    
        
        
    


4.1.14 Sample Data for Q17-Q19

The content of cxml.xml is:


  

4.2 Queries and Results

4.2.1 Q1

Arrange a sequence of items as a table with three columns (using as many rows as necessary).

Solution in XQuery:

declare variable $seq := fn:doc("arrange_rows.xml");

{
  for tumbling window $w in $seq/doc/*
    start at $x when fn:true()
    end at $y when $y - $x = 2
  return
    {
      for $i in $w
      return
        
    }
}
{data($i)}

Expected Result:

Green Pink Lilac
Turquoise Peach Opal
Champagne

4.2.2 Q2

Convert a structure with implicit sections to a structure with explicit sections.

Solution in XQuery:

declare variable $seq := fn:doc("head_para.xml");

{
  for tumbling window $w in $seq/body/*
    start previous $s when $s[self::h2]
    end next $e when $e[self::h2]
  return
    
{ for $x in $w return {data($x)} }
}

Expected Result:


  
para1 para2
para3 para4 para5

4.2.3 Q3

Within a glossary in HTML, a defined term

can be followed by a definition
. The task is to group these together within a element, where a group can consist of one or more
elements followed by one or more
elements.

Solution in XQuery:

declare variable $seq := fn:doc("term_def_list.xml");

{
for tumbling window $w in $seq/doc/*
  start $x when $x[self::dt]
  end $y next $z when $y[self::dd] and $z[self::dt]
return
  {
    $w
  }
}

Expected Result:


  
    
XML
Extensible Markup Language
XSLT
XSL Transformations
A language for transforming XML
A specification produced by W3C

4.2.4 Q4

Calculate the moving average of temperature values for the 3 last seconds.

Solution in XQuery:

declare variable $timesequence := fn:doc("temp_events.xml");

let $MAX_DIFF := 2

for sliding window $w in $timesequence/stream/event
  start  $s_curr at $s_pos previous $s_prev
    when ($s_curr/@time ne $s_prev/@time) or (empty($s_prev))
  only end next $e_next
    when $e_next/@time - $s_curr/@time gt $MAX_DIFF
return
  avg( $w/@temp )

Expected Result:

8 9 17 18

4.2.5 Q5

Single exponential smoothing (3 last values and smoothing factor 0.2)

Solution in XQuery:

declare variable $timesequence := fn:doc("temp_events.xml");
let $SMOOTH_CONST := 0.2

for sliding window $w in $timesequence/stream/event
  start at $s_pos when true()
  only end at $e_pos when $e_pos - $s_pos eq 2
return
  round-half-to-even($SMOOTH_CONST * data($w[3]/@temp) + (1 - $SMOOTH_CONST) *
    ( $SMOOTH_CONST * data($w[2]/@temp) +
      (1 - $SMOOTH_CONST) * data($w[1]/@temp) ), 2)

Expected Result:

8.88 8.68 12.32 15.24 23.92

4.2.6 Q6

Detect outliers (current value is two times higher (lower) than the average of the previous three values) in a sequence of temp values.

Solution in XQuery:

declare variable $seq := fn:doc("temp_events.xml");

for sliding window $w in $seq/stream/event
  start  $s_curr when fn:true()
  only end next $next when $next/@time > $s_curr/@time + 3
return
  let $avg := fn:avg($w/@temp)
  where $avg * 2 lt xs:double($next/@temp) or $avg div 2 gt xs:double($next/@temp)
  return Outlier detected. Event id:{data($next/@time)}

Expected Result:

Outlier detected. Event id:5

4.2.7 Q7

Notify when Barbara enters the building within 1 hour after Anton

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
  for tumbling window $w in $seq/stream/event
    start  $s when $s/person eq "Anton" and $s/direction eq "in"
    only end $e next $n when  xs:dateTime($n/@time) - xs:dateTime($s/@time) gt
      xs:dayTimeDuration("PT1H")
      or  ($e/person eq "Barbara" and $e/direction eq "in")
      or ($e/person eq "Anton" and $e/direction eq "out")
  where $e/person eq "Barbara" and $e/direction eq "in"
  return
    Barbara: Anton arrived 1h ago
}

Expected Result:


  Barbara: Anton arrived 1h ago

4.2.8 Q8

Measure the working time of each person

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
for sliding window $w in $seq/stream/event
  start  $s when $s/direction eq "in"
  only end  $e when $s/person eq $e/person and
    $e/direction eq "out"
return
  
      {$s/person}
      
  
}

Expected Result:


        
                Anton
                
        
        
                Barbara
                
        
        
                Clara
                
        
        
                Anton
                
        
        
                Clara
                
        
        
                Clara
                
        
        
                Clara
                
        
        
                Clara
                
        

4.2.9 Q9

Measure the overall working time for each person.

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
for sliding window $w in $seq/stream/event
  start  $s when $s/direction eq "in"
  only end  $e when $s/person eq $e/person and
    $e/direction eq "out"
let $person := $s/person
let $workingTime := xs:dateTime($e/@time) - xs:dateTime($s/@time)
group by $person
order by $person
return
  
    { $person }
    
  
}

Expected Result:


  
    Anton
    
  
  
    Barbara
    
  
  
    Clara
    
  

4.2.10 Q10

Display a warning if Barbara does not come to work.

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
  for tumbling window $w in $seq/stream/event[direction eq "in"]
    start  $s when fn:true()
    end next $e when xs:date( xs:dateTime($s/@time) ) ne xs:date( xs:dateTime($e/@time) )
  let $date := xs:date(xs:dateTime($s/@time))
  where not($w[person eq "Barbara"])
  return Barbara did not come to work
}

Expected Result:


  Barbara did not come to work

4.2.11 Q11

Identify every person who enters the building before Clara withing a 15 minute timeframe (Clara's arrival time - 15 minutes).

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
  for tumbling window $w in $seq/stream/event[direction eq "in"]
    start when true()
    only end next $x when  $x/person eq "Clara"
  return
    {
      distinct-values(for $y in $w
        where (xs:dateTime($y/@time) + xs:dayTimeDuration("PT15M") ) ge xs:dateTime($x/@time)
        return $y/person)
    }
}

Expected Result:


        Barbara
        
        Clara
        Clara
        


4.2.12 Q12

Notify when both Anton and Barbara enter the office within 30 minutes of one another.

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
        for tumbling window $w in $seq/stream/event[direction eq "in"]
                start  $x when $x/person = ("Barbara", "Anton")
                end next $y when xs:dateTime($y/@time) - xs:dateTime($x/@time) gt xs:dayTimeDuration("PT30M")
        where $w[person eq "Anton"] and $w[person eq "Barbara"]
        return
                Anton and Barbara just arrived
}

Expected Result:


        Anton and Barbara just arrived

4.2.13 Q13

Inform when a person enters the building at least 3 times within 1 hour

Solution in XQuery:

declare variable $seq := fn:doc("person_events.xml");

{
  for sliding window $w in $seq/stream/event
    start  $s when true()
    end next $e when xs:dateTime($e/@time) - xs:dateTime($s/@time) gt
      xs:dayTimeDuration("PT1H")
  where count($w[person eq $s/person and direction eq "in"]) ge 3
  return
    {fn:data($s/person)} is suspicious
}

Expected Result:


  Clara is suspicious

4.2.14 Q14

Find all annoying authors who have posted three consecutive items in the RSS feed.

Solution in XQuery:

declare variable $rssfeed := fn:doc("rss.xml");

{
  for tumbling window $w in $rssfeed/rss/channel/item
    start  $first when fn:true()
    end next $lookAhead when $first/author ne $lookAhead/author
  where count($w) ge 3
  return {
      $w[1]/author
    }
}

Expected Result:

4.2.15 Q15

Every day, provide a list of interesting topics in the RSS feed. In our example, interesting means that the title of the item contains the specific word XQuery.

Solution in XQuery:

declare variable $rssfeed := fn:doc("rss.xml");

{
  for tumbling window $w in $rssfeed/rss/channel/item
    start  $s_curr when true()
    end next $e_next when
      fn:day-from-dateTime(xs:dateTime($e_next/pubDate)) ne
      fn:day-from-dateTime(xs:dateTime($s_curr/pubDate))
  return
    
        {xs:date(xs:dateTime($s_curr/pubDate))}
        {  for $item in $w
                   where fn:contains( xs:string($item/title), 'XQuery')
                   return $item/title   }
      
}

Expected Result:


  
    2003-06-03
    Extending XQuery with Window Functions
    XQueryP: A new programming language is born
  
  
    2003-06-04
  

4.2.16 Q16

Every day, provide a summary of the RSS feed grouped by author.

Solution in XQuery:

declare variable $rssfeed := fn:doc("rss.xml");

{
  for tumbling window $w in $rssfeed/rss/channel/item
    start  $s_curr when true()
    end next $e_next when
      fn:day-from-dateTime(xs:dateTime($e_next/pubDate)) ne
      fn:day-from-dateTime(xs:dateTime($s_curr/pubDate))
  return
    
      {xs:date(xs:dateTime($s_curr/pubDate))}
       {  for $a in fn:distinct-values($w/author)
           return
             
               
                 { $w[author eq $a]/title }
               
                        
            }
          
}

Expected Result:


  
    2003-06-03
    
      
        Why use cases are important Part 1.
        Why use cases are important Part 2.
        Why use cases are important Part 3.
      
    
    
      
        Extending XQuery with Window Functions
      
    
    
      
        XQueryP: A new programming language is born
      
    
  
  
    2003-06-04
    
      
        Why use cases are annoying to write.
      
    
  

4.2.17 Q17

At the end of a day, list the most valuable customers.

Solution in XQuery:

declare variable $seq := fn:doc("cxml.xml");

{
for sliding window $w in $seq/sequence/*
  start  $cur previous $prev
   when day-from-dateTime($cur/@date) ne day-from-dateTime($prev/@date) or empty($prev)
  end $end next $next
   when day-from-dateTime(xs:dateTime($end/@date)) ne
day-from-dateTime(xs:dateTime($next/@date))
return
  {
    let $companies :=   for $x in distinct-values($w/@billTo )
                        return {sum($w[@billTo eq $x]/@total)}
    let $max := max($companies)
    for $company in $companies
    where $company eq xs:untypedAtomic($max)
    return $company
  }
}

Expected Result:


  
    1100
  
  
    10000
  
  
  
  
  
    100
  
  

4.2.18 Q18

Calculate the time needed to process an order from the request up to the shipping.

Solution in XQuery:

declare variable $seq := fn:doc("cxml.xml");

{
  for sliding window $w in $seq/sequence/*
    start $s when $s[self::OrderRequest]
    end   $e when $e/@orderID eq  $s/@orderID
             and ($e[self::ConfirmationRequest] and $e/@status eq "reject"
                  or $e[self::ShipNotice])
  where $e[self::ShipNotice]
  return
    {xs:dateTime($e/@date) - xs:dateTime($s/@date) }
}

Expected Result:


  P3DT22H
  P2DT19H

4.2.19 Q19

At the moment of the shipping notification, calculate if an open request exists that can be shipped to the same address.

Solution in XQuery:

declare variable $seq := fn:doc("cxml.xml");

{
  for sliding window $w in $seq/sequence/*
    start previous $wSPrev when $wSPrev[self::OrderRequest]
    end next $wENext when $wENext/@orderID eq  $wSPrev/@orderID
        and ($wENext[self::ConfirmationRequest] and $wENext/@status eq "reject"
                 or $wENext[self::ShipNotice])
  where $wENext[self::ShipNotice]
  return
    {
        for sliding window $bundle in $w
          start  $bSCur
            when $bSCur[self::OrderRequest] and $bSCur/@shipTo eq $wSPrev/@shipTo
          end  $bECur next $bENext
            when $bECur/@orderID eq  $bSCur/@orderID
             and ($bECur[self::ConfirmationRequest] and $bECur/@status eq "reject"
              or $bECur[self::ShipNotice])
          where empty($bENext)
          return $bSCur
    }
}

Expected Result:


  
    
      
    
  
  

5 Use Case "Count" - Queries which require output numbering

The described queries in this section all require tuple numbering. The numbering is either required in the final result or might also be required at some point in the middle when the tuple stream gets generated.

5.1 Schema and Sample Data

The "Count" use cases are all based on the shopping scenario which can be found in the section Shopping Scenario Schema and Data.

5.2 Queries and Results

5.2.1 Q1

List all products in alphabatical order with a continously increasing number.

Solution in XQuery:

{
    for $product in doc("products.xml")/*/product
    order by $product/name
    count $number
    return
        {$product/*}
}

Expected Result:


    
        blender
        kitchen
        50
        25
    
    
        broiler
        kitchen
        100
        70
    
    
        shirt
        clothes
        10
        3
    
    
        socks
        clothes
        5
        2
    
    
        toaster
        kitchen
        30
        10
    

5.2.2 Q2

Arrange a sequence of items as a table with three columns (using as many rows as necessary) like in Q1 from the windowing use cases.Additionally, number every row continuously.

Solution in XQuery:

declare variable $seq := fn:doc("arrange_rows.xml");

{
  for tumbling  window $w in $seq/doc/*
    start at $x when fn:true()
    end at $y when $y - $x = 2
  count $rowNumber
  return
    {
      for $i in $w
      return
        
    }
}
{$rowNumber}{data($i)}

Expected Result:

1 Green Pink Lilac
2 Turquoise Peach Opal
3 Champagne

5.2.3 Q3

Top-K query: Return the three best-selling products (by quantity).

Solution in XQuery:

{
    for $sales in doc("sales-records.xml")/*/record
    let $name := $sales/product-name
    group by $name
    let $qty := sum($sales/qty)
    order by $qty descending
    count $count
    where $count <= 3
    return
        
}

Expected Result:


    
    
    

6 Use Case "Outer For" - Queries which require outer joins

This use case demonstrate how the new "outer for" clause can help to express outer joins in XQuery.

6.1 Schema and Sample Data

The "Outer For" use case is based on the shopping scenario which can be found in the section Shopping Scenario Schema and Data.

6.2 Queries and Results

6.2.1 Q1

Report all the store sales including stores which have not sold anything.

Solution in XQuery:

{
    for $store in doc("stores.xml")/*/store
    for $sale allowing empty in doc("sales-records.xml")/*/record[
         store-number eq $store/store-number]
    return
      
}

Expected Result:


    
    
    
    
    
    
    
    
    
    

6.2.2 Q2

List all the sales records. Include also all the items which were not sold in a store.

Solution in XQuery:

{
for $store in doc("stores.xml")/*/store
for $product in doc("products.xml")/*/product
for $sale allowing empty in doc("sales-records.xml")/*/record[
     store-number eq $store/store-number and
     product-name eq $product/name]
return
  
}

Expected Result:



    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    


7 Use Case "Try-Catch" - Queries which require to recover from errors

This use case covers queries that require to recover from errors.

7.1 Sample Data

Q1 and Q2 are based on a errornous version of product.xml from Shopping Scenario Schema and Data, whereas Q3 does not require any input data. Sample data for Q1 and Q2 named product-err.xml are shown below:


  
    broiler
    kitchen
    100
    "70"
  
  
    toaster
    kitchen
    30
    10
  
  
    blender
    kitchen
    50
    25
  
  
    socks
    clothes
    5
    2
  
  
    shirt
    clothes
    10
    3
  

7.2 Queries and Results

7.2.1 Q1

Calculate the margin of every product. If an error occurs, report a user-friendly message.

Solution in XQuery:

try {
    {
        for $product in fn:doc("product-err.xml")//product
        return
            {$product/name}
            {$product/price - $product/cost}
            
    }
} catch * {
     "An error occured, please ask your consultant for help."
}

Expected Result:

An error occured, please ask your consultant for help.

7.2.2 Q2

Report the margin in procent of every product. If an error occurs the failure should be listed, but the query should still continue to report the other values.

Solution in XQuery:

{
    for $product in fn:doc("product-err.xml")//product
    return
         try {
            {$product/name}
              {$product/price div $product/cost}
            
        } catch * {
            {
                ($product/name, "Error:", $err:code)
            }
        }
}

Expected Result:



    
        broiler
        Error: FORG0001
    
    
        toaster
        3
    
    
        blender
        2
    
    
        socks
        2.5
    
    
        shirt
        3.3333333333333333
    

7.2.3 Q3

For a sequence of inputs the n-th fibonacci number has to be calculated using a pre-defined function. The function is built to avoid long running times and therefore rejects high values by throwing a user-defined error. If such an error occurs during calculation, a warning should be displayed, but the processing should continue.

Solution in XQuery:

declare namespace foo='http://foo.com';
declare function local:fib-recur($n as xs:integer) as xs:integer? {
    if ($n <0) then ()
    else if ($n > 100) then
        fn:error(fn:QName('http://foo.com', 'ValueToBig'), 'Value too big')
    else if ($n = 0)  then 0
    else if ($n=1)   then 1
    else local:fib-recur($n - 1)  + local:fib-recur($n - 2)
};

{
    for $x in (3,1,1030,5)
    return
        try{
        {local:fib-recur($x)}
        }catch foo:ValueToBig {
          Number to big
        }
}

Expected Result:



    2
    1
    Number to big
    5

A Acknowledgements (Non-Normative)

The Working Group thanks the following individuals for their contributions:

Peter M. Fischer, Donald Kossmann, Rokas Tamosevicius Use Case "windowing"

B Change Log (Non-Normative)

B.1 30 Mar 2011

  • Removed xsi declaration and xsi:noNamespaceSchemaLocation attributes in input documents. Resolves BZ 11757.

  • Corrected input file name in Windowing Q7. Resolves BZ 11756.

  • Corrected Clara's working time in Windowing Q8. Resolves BZ 11758.

  • Added order by $person to Windowing Q9. Resolves BZ 11759.

  • Corrected Clara's working time in Windowing Q9. Resolves BZ 11853.

  • Corrected result of Windowing Q12. Resolves BZ 11761.

  • Added parentheses to correct solutions in Windowing Q18 and Q19. Resolves BZ 11762.

B.2 30 January 2008

  • Added group-by UC.

  • Added windowing UC.

B.3 17 November 2008

  • Added try-catch UC.

  • Added outer-join UC.

  • Added output-numbering UC.

  • Changed all DTDs to XML Schema.

C References (Non-Normative)

The following references are some of the works considered by the WG in deriving its use cases.

XMLSchema0
XML Schema Part 0: Primer Second Edition, David Fallside and Priscilla Walmsley, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-0/.
XMLSchema1
XML Schema Part 1: Structures Second Edition, Henry Thompson, David Beech, Murray Maloney, and Noah Mendelsohn, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-1/.
XMLSchema2
XML Schema Part 2: Datatypes Second Edition, Paul V. Biron and Ashok Malhotra, Editors. World Wide Web Consortium, 28 Oct 2004. This version is http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/. The latest version is available at http://www.w3.org/TR/xmlschema-2/.
XQuery 3.0
XQuery 3.0: An XML Query Language, Jonathan Robie, Don Chamberlin, Michael Dyck, John Snelson, Editors. World Wide Web Consortium, 08 April 2014. This version is http://www.w3.org/TR/2014/REC-xquery-30-20140408/. The latest version is available at http://www.w3.org/TR/xquery-30/.
XQuery 3.0 Requirements
XQuery 3.0 Requirements, Daniel Engovatov, Jonathan Robie, Editors. World Wide Web Consortium, 08 April 2014. This version is http://www.w3.org/TR/2014/NOTE-xquery-30-requirements-20140408/. The latest version is available at http://www.w3.org/TR/xquery-30-requirements/.
XSL Transformations (XSLT) Version 3.0
XSL Transformations (XSLT) Version 3.0, Michael Kay, Editor. World Wide Web Consortium, 12 December 2013. This version is http://www.w3.org/TR/2013/WD-xslt-30-20131212/. The latest version is available at http://www.w3.org/TR/xslt-30/.
Use Case Sample Queries
Queries from this document, presented in a single file