Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dense_Rank does not work as it is expected

I’m creating a query where I need to get the ranking depending on how many are duplicated in the column "MacAddress"(amount) in the table MacsUsers, this is the data:
enter image description here

this is my SQL query:

SELECT
COUNT([MU].MacAddress) AS Quantity,
[USER].Name,
[USER].SurName,
[MU].MacAddress,
DENSE_RANK() OVER(ORDER BY mu.MacAddress) AS RNK

FROM MacsUsers [MU]
JOIN Macs [MAC] ON [MAC].MacAddress = [MU].MacAddress
JOIN Users [USER] ON [MAC].UserEmail = [USER].Email
JOIN Profiles [PROFILE] ON [PROFILE].MacAddress = [MAC].MacAddress

GROUP BY mu.MacAddress,[USER].Name,
[USER].SurName

I think I’m doing well with the DENSE_RANK function but it does not work as it is expected, any possible solution? thanks advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your DENSE_RANK window function should apply ordering on the "Quantity" field instead of the "MacAddress" field. In order to apply a window function on an aggregated field, you need to have a subquery as follows.

WITH cte AS (
    SELECT COUNT([MU].MacAddress) AS Quantity,
           [USER].Name,
           [USER].SurName,
           [MU].MacAddress
    FROM MacsUsers [MU]
    JOIN Macs [MAC] ON [MAC].MacAddress = [MU].MacAddress
    JOIN Users [USER] ON [MAC].UserEmail = [USER].Email
    JOIN Profiles [PROFILE] ON [PROFILE].MacAddress = [MAC].MacAddress
    GROUP BY mu.MacAddress,
             [USER].Name,
             [USER].SurName
) 
SELECT *, DENSE_RANK() OVER(ORDER BY Quantity) AS RNK 
FROM cte 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading