4

我有以下工作,但我认为我已经完成了我通常的技巧,即过度复杂化可能更简单的事情。

如果您运行该脚本,您将看到我想要实现的目标 - 最初按部门分数排名,然后按每个部门内每个姓名的分数排名。

如何简化以下内容?:

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
4

1 回答 1

8

有一个更简单的方法。试试这个:

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
于 2013-02-21T16:23:00.147 回答