Thursday, September 5, 2019

How to use NTILE(), CUME_DIST (), PERCENT_RANK() functions

DECLARE @empDept AS TABLE (empID INT IDENTITY(1,1), firstName VARCHAR(250), lastName VARCHAR(250), Department VARCHAR(250), rate DECIMAL(9,2))

INSERT INTO @empDept (firstName, lastName, Department, rate) 
VALUES
 ('Hima', 'Arifin'          ,'Document Control',       17.7885)  
,('James', 'Norred'          ,'Document Control',       16.8269)  
,('Saket', 'Kharatishvili'   ,'Document Control',       16.8269)  
,('Hung', 'Chai'            ,'Document Control',       10.25  )  
,('Kethrine', 'Berge'           ,'Document Control',       10.25  )  
,('Tim', 'Trenary'         ,'Information Services',       50.4808)  
,('Pole', 'Conroy'          ,'Information Services',       39.6635)  
,('Andrew', 'Ajenstat'        ,'Information Services',       38.4615)  
,('Jack', 'Wilson'          ,'Information Services',       38.4615)  
,('Mohit', 'Sharma'          ,'Information Services',       32.4519)  
,('Lara', 'Connelly'        ,'Information Services',       32.4519)  
,('Peter', 'Berg'            ,'Information Services',       27.4038)  
,('Lune', 'Meyyappan'       ,'Information Services',       27.4038)  
,('Jamy', 'Bacon'           ,'Information Services',       27.4038)  
,('Walter', 'Bueno'           ,'Information Services',       27.4038)  

--SELECT * FROM @empDept

SELECT FirstName, LastName, Department, rate
, NTILE(5) OVER(PARTITION BY Department ORDER BY rate DESC) AS Quartile
FROM @empDept

SELECT edh.Department, edh.LastName, edh.Rate,  
       CUME_DIST () OVER (PARTITION BY edh.Department ORDER BY edh.Rate) AS CumeDist,  
       PERCENT_RANK() OVER (PARTITION BY edh.Department ORDER BY edh.Rate ) AS PctRank 
FROM @empDept AS edh 
    INNER JOIN @empDept AS e   
    ON e.empID = edh.empID 
WHERE edh.Department IN (N'Information Services',N'Document Control')  
ORDER BY edh.Department, edh.Rate DESC;

No comments: