w3resource

AdventureWorks Database: Specify which groups to include in the results

SQL Query - AdventureWorks: Exercise-18 with Solution

18. From the following table write a query in SQL to retrieve the total sales for each year. Filter the result set for those orders where order year is on or before 2016. Return the year part of orderdate and total due amount. Sort the result in ascending order on year part of order date.

Sample table: Sales.SalesOrderHeader


Click to view Full table

Sample Solution:

SELECT DATE_PART('year',OrderDate) AS YearOfOrderDate  
    ,SUM(TotalDue) AS TotalDueOrder  
FROM Sales.SalesOrderHeader  
GROUP BY DATE_PART('year',OrderDate)  
HAVING DATE_PART('year',OrderDate) <= '2016'  
ORDER BY DATE_PART('year',OrderDate);

Sample Output:

yearoforderdate|totaldueorder|
---------------+-------------+
         2011.0|14155699.5250|
         2012.0|37675700.3120|
         2013.0|48965887.9632|
         2014.0|22419498.3157|

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Sales by year using GROUP BY with an expression.
Next: Contacts designated as a manager.

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