w3resource

AdventureWorks Database: GROUP BY CUBE operation on locationid and shelf

SQL Query - AdventureWorks: Exercise-13 with Solution

13. From the following table write a query in SQL to find the sum of the quantity of all combination of group of distinct locationid and shelf column. 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 CUBE (locationid, shelf);

Sample Output:

locationid|shelf|totalquantity|
----------+-----+-------------+
          |     |       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|
        10|C    |         3464|
		...

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Calculate running totals and subtotals.
Next: Combining multiple GROUP BY clauses into one.

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

How to create a foreign key in SQL Server?

create table question_bank
(
    question_id uniqueidentifier primary key,
    question_exam_id uniqueidentifier not null,
    question_text varchar(1024) not null,
    question_point_value decimal,
    constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
);

Database: SQL Server

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