sequence查询中的排名

时间:2017-06-30 07:51:44

标签: sql-server tsql

我想在mssql中获取序列号。请参阅下文。

有一张桌子。

UserID     Score      TeamID
------------------------------
1          100         1
2          200         1
3          500         2
4          600         2
5          700         2
6          1000        3

我想按团队总分进行排序。见下文

RankID       UserID        Score     TeamID      TotalScore
-----------------------------------------------------------
1            3             500       2           1800           
1            4             600       2           1800
1            5             700       2           1800  
2            6             1000      3           1000
3            1             100       1           300
3            2             200       1           300

我想只编写一个sql查询。帮帮我一个人怎么办?感谢。

3 个答案:

答案 0 :(得分:3)

这应该有效:

;WITH TotalScore AS (
  SELECT UserID, Score, TeamID,
    SUM(Score) OVER (PARTITION BY TeamID) AS TotalScore
   FROM mytable
)
SELECT DENSE_RANK() OVER (ORDER BY TotalScore DESC) AS RankID,
  UserID, Score, TeamID, TotalScore   
FROM TotalScore
ORDER BY TotalScore DESC, Score

使用的公用表表达式使用窗口版TeamID计算每SUM的总得分。将DENSE_RANK与此计算字段一起使用,我们可以轻松生成所需的RankID

答案 1 :(得分:1)

你可以试试这个

SELECT
RANK() OVER(ORDER BY i.TotalScore DESC) AS RankID
,A.*
FROM
(
    SELECT
     UserID
    ,Score
    ,TeamID
    ,(SELECT SUM(Score) FROM yourTable tb2 WHERE tb2.TeamID = tb1.TeamID) AS TotalScore
FROM yourTable tb1
) A
ORDER BY A.TotalScore DESC

答案 2 :(得分:0)

尝试以下,

Select DENSE_RANK() over(Order by (Select Sum(Score) from @tablename V where V.TeamID=T.TeamID ) desc )RankID
,*,
Sum(Score) over(Partition by TeamID) TotalScore from @tablename T
order by DENSE_RANK() over(Order by (Select Sum(Score) from @tablename V where V.TeamID=T.TeamID ) desc )

“排序依据”中的密集排名按RANK Id对结果进行排序,并且在Select语句中使用相同排名,密集排名中的子查询将根据TeamID的总和(分数)进行排名