2013-02-21 83 views
3

我有以下這些工作,但我認爲我已經完成了我通常的技巧,使複雜的事情可能更簡單。RANK分區函數與SUM OVER一起使用

如果您運行該腳本,您將看到我想要實現的功能 - 僅根據部門評分初步排名,然後按每個部門中每個名稱的評分排名。

如何簡化下面?:

IF OBJECT_ID('TEMPDB..#Table') IS NOT NULL BEGIN DROP TABLE #Table END; 
CREATE TABLE #Table 
    (
    Department VARCHAR(100), 
    Name VARCHAR(100), 
    Score INT 
    ); 

INSERT INTO #Table VALUES 
('Sales','michaeljackson',7), 
('Sales','jim',10), 
('Sales','jill',66), 
('Sales','j',1),  
('DataAnalysis','jagoda',66), 
('DataAnalysis','phil',5), 
('DataAnalysis','jesus',6), 
('DataAnalysis','sam',79), 
('DataAnalysis','michaeljackson',9999); 

WITH SumCte AS 
    (
    SELECT Department, 
     sm = sum(Score) 
    FROM #Table 
    GROUP BY Department 
    ) 
, RnkDepCte AS 
    (
    SELECT Department, 
     rk =RANK() OVER (ORDER BY sm DESC) 
    FROM SumCte 
    ) 
, RnkCte AS 
    (
    SELECT Department, 
     Name, 
     Score, 
     rnk = RANK() OVER (PARTITION BY a.Department ORDER BY a.Score DESC) 
    FROM #Table a 
    ) 
SELECT a.Department, 
     a.Name, 
     a.Score, 
     FinalRank = RANK() OVER (ORDER BY ((10000/b.rk) + (100/a.rnk)) DESC) 
FROM RnkCte a 
     INNER JOIN RnkDepCte b 
     ON a.Department = b.Department 

回答

7

有一個簡單的方法。試試這個:

select t.*, 
     RANK() over (order by sumscore desc, score desc) 
from (select t.*, 
      SUM(score) over (partition by department) as SumScore 
     from #Table t 
    ) t 
+0

+1無法想象任何人會有任何更簡單的建議! – whytheq 2013-02-21 16:27:57