Hi @Carlton Patterson ,
Welcome to microsoft TSQL Q&A forum!
Your code is correct.It did get the expected output result you provided:
SELECT
SubQuery.department
,SubQuery.salary
,myrank
FROM (SELECT
twitter_employee.department
,twitter_employee.salary
,DENSE_RANK() OVER (PARTITION BY twitter_employee.department ORDER BY twitter_employee.salary DESC) AS myrank
FROM dbo.twitter_employee
GROUP BY twitter_employee.department
,twitter_employee.salary) SubQuery
Output:
department salary myrank
Audit 110000 1
Audit 100000 2
Audit 70000 3
Management 250000 1
Management 200000 2
Management 150000 3
Management 100000 4
Sales 220000 1
Sales 200000 2
Sales 150000 3
Sales 140000 4
Sales 130000 5
Sales 120000 6
Sales 100000 7
However, it is worth noting that in DENSE_RANK() OVER (PARTITION BY twitter_employee.department ORDER BY twitter_employee.salary DESC), order by is only used to indicate the order in which to rank, and cannot determine the order of the final result.
If you don't want to add the myrank column to the select list, you need to add an order by clause at the end of the query according to Paul Staniforth-8963.
In addition, you can use cte instead of subqueries, which seems to be easier to read:
;WITH cte
as(SELECT department,salary,
DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS myrank
FROM dbo.twitter_employee
GROUP BY department,salary)
SELECT department,salary
FROM cte
ORDER BY department,salary Desc
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.