w3resource

AdventureWorks Database: Calculate running totals and subtotals

SQL Query - AdventureWorks: Exercise-12 with Solution

12. From the following table write a query in SQL to find the sum of subtotal column. Group the sum on distinct salespersonid and customerid. Rolls up the results into subtotal and running total. Return salespersonid, customerid and sum of subtotal column i.e. sum_subtotal.

Sample table: sales.salesorderheader


Click to view Full table

Sample Solution:

SELECT salespersonid,customerid,sum(subtotal) AS sum_subtotal
FROM sales.salesorderheader s 
GROUP BY ROLLUP (salespersonid, customerid);

Sample Output:

salespersonid|customerid|sum_subtotal  |
-------------+----------+--------------+
          274|     29491|    33406.7043|
          274|     29493|      2146.962|
          274|     29514|     3405.1668|
          274|     29523|    34349.2656|
          274|     29576|        53.994|
          274|     29579|      35331.66|
          274|     29604|       647.994|
          274|     29605|    29482.0603|
          274|     29616|   138046.3212|
          274|     29617|   198993.3507|
          274|     29623|      1946.022|
          274|     29650|        83.988|
          274|     29666|    15842.6141|
          274|     29669|     3962.2441|
          274|     29671|     11802.564|
          274|     29675|       4254.45|
		  ...

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Persons whose last name begins with 'L'.
Next: GROUP BY CUBE operation on locationid and shelf.

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