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:

          |     |       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|

SQL AdventureWorks Editor:

Practice Online

Contribute your code and comments through Disqus.

Previous: GROUP BY CUBE operation on locationid and shelf.
Next: Empty group as one of the elements of a GROUPING SET.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

SQL: Tips of the Day

T-SQL Cast versus Convert?

CONVERT is SQL Server specific, CAST is ANSI.

CONVERT is more flexible in that you can format dates etc. Other than that, they are pretty much the same. If you don't care about the extended features, use CAST.

Ref : https://bit.ly/3VKT5M8