w3resource

AdventureWorks Database: Find the average and sum of the subtotal

SQL Query - AdventureWorks: Exercise-8 with Solution

8. From the following table write a query in SQL to find the average and the sum of the subtotal for every customer. Return customerid, average and sum of the subtotal. Grouped the result on customerid and salespersonid. Sort the result on customerid column in descending order.

Sample table: sales.salesorderheader


Click to view Full table

Sample Solution:

SELECT customerid,salespersonid,AVG(subtotal) AS avg_subtotal,
SUM(subtotal) AS sum_subtotal 
FROM sales.salesorderheader 
GROUP BY customerid,salespersonid
ORDER BY customerid DESC;

Sample Output:

customerid|salespersonid|avg_subtotal          |sum_subtotal|
----------+-------------+----------------------+------------+
     30118|          275|    34638.152183333333| 207828.9131|
     30118|          277|    35369.828450000000|  70739.6569|
     30117|          275|    77171.792833333333| 463030.7570|
     30117|          277|    58954.136550000000| 353724.8193|
     30116|          276|    46778.550275000000| 187114.2011|
     30115|          289| 1114.6949250000000000|   8917.5594|
     30114|          290| 1456.6238875000000000|  11652.9911|
     30113|          282|    34148.236350000000| 273185.8908|
     30112|          280|    93591.621700000000|  93591.6217|
     30112|          284|    54909.378542857143| 384365.6498|
     30111|          277|    69131.600775000000| 276526.4031|
     30110|          276|  406.3188750000000000|   1625.2755|
     30109|          275|    59857.260500000000|  119714.521|
     30109|          277|    36114.523283333333| 216687.1397|
     30108|          289|    36150.645400000000| 144602.5816|
	 ...

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Calculate the total freight paid by each customer.
Next: Find total quantity of each product in specific shelves.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

SQL: Tips of the Day

How to avoid the "divide by zero" error in SQL?

Select Case when divisor=0 then null
Else dividend / divisor
End ,,,

OR:

Select dividend / NULLIF(divisor, 0) ...

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

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook