我有以下工作,但我认为我已经完成了我通常的技巧,即过度复杂化可能更简单的事情。
如果您运行该脚本,您将看到我想要实现的目标 - 最初按部门分数排名,然后按每个部门内每个姓名的分数排名。
如何简化以下内容?:
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