w3resource

AdventureWorks Database: Return first and last name, and other columns using partition by clause

SQL Query - AdventureWorks: Exercise-123 with Solution

123 From the following table write a query in SQL to return first name, last name, territoryname, salesytd, and row number. Partition the query result set by the TerritoryName. Orders the rows in each partition by SalesYTD. Sort the result set on territoryname in ascending order.

Sample table: Sales.vSalesPerson


Click to view Full table

Sample Solution:

SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2) AS SalesYTD,  
ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC) 
  AS Row  
FROM Sales.vSalesPerson  
WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0  
ORDER BY TerritoryName;

Sample Output:

firstname|lastname         |territoryname |salesytd  |row|
---------+-----------------+--------------+----------+---+
Lynn     |Tsoflias         |Australia     |1421810.92|  1|
José     |Saraiva          |Canada        |2604540.72|  1|
Garrett  |Vargas           |Canada        |1453719.47|  2|
Jillian  |Carson           |Central       |3189418.37|  1|
Ranjit   |Varkey Chudukatil|France        |3121616.32|  1|
Rachel   |Valdez           |Germany       |1827066.71|  1|
Michael  |Blythe           |Northeast     |3763178.18|  1|
Tete     |Mensa-Annan      |Northwest     |1576562.20|  1|
David    |Campbell         |Northwest     |1573012.94|  2|
Pamela   |Ansman-Wolfe     |Northwest     |1352577.13|  3|
Tsvi     |Reiter           |Southeast     |2315185.61|  1|
Linda    |Mitchell         |Southwest     |4251368.55|  1|
Shu      |Ito              |Southwest     |2458535.62|  2|
Jae      |Pak              |United Kingdom|4116871.23|  1|

SQL AdventureWorks Editor:

Practice Online


Contribute your code and comments through Disqus.

Previous: Calculate row numbers for rows between 50 to 60 inclusive.
Next: Order the result set by the column TerritoryName using CASE.


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

Convert Timestamp to date in MySQL Query:

DATE_FORMAT(FROM_UNIXTIME(`user.registration`), '%e %b %Y') AS 'date_formatted'

Database: MySQL

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