Database Reference
In-Depth Information
SELECT
?emp (COUNT(DISTINCT ?orderNo) AS ?ordersByEmployee)
WHERE
{
?sales a ex:Sales ; ex:Sales#Employee ?emp ;
ex:Sales#OrderNo ?orderNo .
?emp a ex:Employee .
}
GROUP BY ?emp
HAVING COUNT(DISTINCT ?orderNo) > 100
ORDER BY DESC(COUNT(DISTINCT ?orderNo))
The GROUP BY clause collects the orders associated with each employee, the
HAVING clause keeps only the employees who have more than 100 distinct
orders, and the ORDER BY clause orders the result in descending order
according to the number of orders.
Consider now the query “For customers from San Francisco, list the total
quantity of each product ordered. Order the result by customer key, in
ascending order, and by quantity of products ordered, in descending order.”
SELECT
?cust ?prod (SUM(?qty) AS ?totalQty)
WHERE
{
?sales a ex:Sales ; ex:Sales#Customer ?cust ;
ex:Sales#Product ?prod ; ex:Sales#Quantity ?qty .
?cust a ex:Customer ; ?ex:Customer#City ?city .
?city a ex:City ; ex:City#Name ?cityName .
FILTER(?cityName = '' San Francisco '' )
}
GROUP BY ?cust ?prod
ORDER BY ASC(?cust) DESC(?totalQty)
This query defines a graph pattern linking sales to customers and cities. Prior
to grouping, we need to find the triples satisfying the graph pattern and select
the customers from San Francisco. We then group by pairs of ?cust and ?prod
and, for each group, take the sum of the attribute ?qty . Finally, the resulting
triples are ordered.
Subqueries
In SPARQL, a subquery is used to look for a certain value in a database and
then use this value in a comparison condition. A subquery is a query enclosed
into curly braces used within a WHERE clause. The external query is called
the outer query.
As an example, let us consider the query “For each customer compute
the maximum sales amount among all her orders.” The query is written as
follows:
SELECT
?cust (MAX(?totalSales) as ?maxSales)
WHERE
{{
SELECT
?cust ?orderNo (SUM(?sales) as ?totalSales)
WHERE
{
?sales a ex:Sales ; ex:Sales#Customer ?cust ;
ex:Sales#OrderNo ?orderNo ; ex:Sales#SalesAmount ?sales .
?cust a ex:Customer .
}
GROUP BY ?cust ?orderNo
}}
GROUP BY ?cust
Search WWH ::




Custom Search