﻿ AdventureWorks: Combining multiple GROUP BY clauses into one

# AdventureWorks Database: Combining multiple GROUP BY clauses into one

## SQL Query - AdventureWorks: Exercise-14 with Solution

14. From the following table write a query in SQL to find the sum of the quantity with subtotal for each locationid. Group the results for all combination of distinct locationid and shelf column. Rolls up the results into subtotal and running total. Return locationid, shelf and sum of quantity as TotalQuantity.

Sample table: production.productinventory

Click to view Full table

Sample Solution:

``````SELECT locationid, shelf, SUM(quantity) AS TotalQuantity
FROM production.productinventory
GROUP BY GROUPING SETS ( ROLLUP (locationid, shelf), CUBE (locationid, shelf) );
``````

Sample Output:

```locationid|shelf|totalquantity|
----------+-----+-------------+
|     |       335974|
|     |       335974|
50|J    |         3321|
6|A    |         2734|
50|B    |         3591|
5|A    |         6572|
45|N/A  |          332|
60|K    |          107|
10|D    |         1727|
60|G    |         1050|
60|A    |         1116|
20|B    |          355|
50|S    |         1333|
50|K    |         8881|
1|G    |         3954|
6|K    |          164|
20|A    |         1680|
...
```

## Practice Online

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿