Question

I have a requirement where I have the data as

StageID         Department Number       UserEmail

732                60012                user1@testing.com
733                60012                user1@testing.com
734                60012                user1@testing.com
735                60012                user2@testing.com
736                60012                user2@testing.com
737                60013                user3@testing.com   
738                60013                user3@testing.com

I want to get the output like this

StageID         Department Number       UserEmail       DRank

732              60012              user1@testing.com   1
733              60012              user1@testing.com   1
734              60012              user1@testing.com   1
735              60012              user2@testing.com   2
736              60012              user2@testing.com   2
737              60013              user3@testing.com   1
738              60013              user3@testing.com   1

I want the combination of DepartmentNumber and UserEmail to be considered when ranking the records. I am using DENSE_RANK() over partition to achieve this, but somehow I am not able to get my desired output. I am not sure where I am going wrong. Could anyone please help me in this

This is the query I used

SELECT StageID, DepartmentNumber, UserEmail
        ,DENSE_RANK() OVER (PARTITION BY DepartmentNumber, UserEmail
         ORDER BY DepartmentNumber, UserEmail ASC) AS DRANK 
   FROM mytable 
Was it helpful?

Solution

I think you want this (SQLFiddle supplied by JW):

SELECT StageID, DepartmentNumber, UserEmail
        ,DENSE_RANK() OVER (PARTITION BY DepartmentNumber
         ORDER BY UserEmail ASC) AS DRANK 
   FROM mytable 

Protip - You never want the same columns in both the PARTITION BY and ORDER BY clauses.

This is if I've understood your requirements. I think you want each departments rows to be ranked independently, and the column to select ranks as the email. If that's not your requirement, you need to be more explicit than

I want the combination of DepartmentNumber and UserEmail to be considered when ranking the records.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top