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
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.
SQL: Tips of the Day
Is SQL syntax case sensitive?
The SQL Keywords are case-insensitive (SELECT, FROM, WHERE, etc), but are often written in all caps. However in some setups table and column names are case-sensitive. MySQL has a configuration option to enable/disable it. Usually case-sensitive table and column names are the default on Linux MySQL and case-insensitive used to be the default on Windows, but now the installer asked about this during setup. For MSSQL it is a function of the database's collation setting.
Ref: https://bit.ly/3R2iyNZ
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
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