使用sql查询以什么方式/方法获得这种结果。
将评委分数排列给每位参赛者,对决赛选手进行排序,显示最终排名。
这个@Prince Jea,给出了一个解决方案,但它不是我一直期待的实际结果,尽管它是正确的。不过,我正在寻找所需的输出。
SQL QUERY
SELECT ContestantID,JudgeID,ScorePoints,
RANK() OVER (ORDER BY ScorePoints DESC) AS xRank,
DENSE_RANK() OVER (ORDER BY ScorePoints DESC) AS fRank
FROM
(
SELECT ContestantID , ScorePoints, JudgeID
FROM Score
) AS a
ORDER BY 1
结果
我更喜欢SQL Fiddle上的一些材料 http://www.sqlfiddle.com/#!6/30d03/2
答案 0 :(得分:1)
第一个CTE正在对Judge栏进行PIVOT
第二次CTE根据判断分数计算每位参赛者的等级
第三次CTE计算每位参赛者的最终得分
; WITH CTE
AS
(
SELECT ContestantID,
MAX(CASE when JudgeID =1 THEN ScorePoints END ) as [JudgeID#1],
MAX(CASE when JudgeID =2 THEN ScorePoints END ) as [JudgeID#2],
MAX(CASE when JudgeID =3 THEN ScorePoints END ) as [JudgeID#3]
FROM Score
Group by ContestantID
)
, CTE2 AS
(
SELECT ContestantID,
[JudgeID#1],
RANK() OVER ( Order by JudgeID#1 desc ) as 'Rank#1',
[JudgeID#2],
RANK() OVER ( Order by JudgeID#2 desc ) as 'Rank#2',
[JudgeID#3],
RANK() OVER ( Order by JudgeID#3 desc ) as 'Rank#3'
FROM CTE
)
, CTE3 as
(
SELECT ContestantID,
SUM (Rank#1+ Rank#2 + Rank#1) as total
FROM CTE2
GROUP BY ContestantID
)
SELECT CTE2.*, CTE3.total as 'Final Score'
FROM CTE2
JOIN CTE3
ON CTE2.ContestantID = CTE3.ContestantID
ORDER BY ContestantID
答案 1 :(得分:1)
这是一个动态的透视查询,适用于任何裁判员。枢轴代码改编自https://stackoverflow.com/a/12505138/3574819。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@cols2 AS NVARCHAR(MAX),
@cols3 AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ', ' + QUOTENAME(JudgeID)
from Score
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @cols2 = STUFF((SELECT distinct '+' + QUOTENAME('rn' + CONVERT(varchar(1),JudgeID))
from Score
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @cols3 = STUFF((SELECT distinct ', ' + QUOTENAME(JudgeID) + ', rank() over (order by ' + QUOTENAME(JudgeId) + ' desc) ' + QUOTENAME('rn' + CONVERT(varchar(1),JudgeID))
from Score
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT * ,
rank() over (order by ' + @cols2 + ') rn,
( ' + @cols2 + ' ) fn
FROM (SELECT ContestantID,' + @cols3 + ' from
(
select ContestantID, ScorePoints, JudgeID
from Score
) x
pivot
(
max(ScorePoints)
for JudgeID in (' + @cols + ')
) p ) t1'
execute(@query)