如果我有这张桌子:
UserID | Score1 | Score2
1 | 10 | 5
2 | 50 | 15
3 | 30 | 25
1 | 50 | 10
2 | 0 | 100
3 | 1 | 5
我想将此表排序为得分1 +得分2,但我也希望得到单独的分数。
但必须按userId分组,并且只返回用户的最高分(因此MAX得分1 +得分2)。
但我不能做一个小组,因为那时我将排除具有相同分数的用户。这对我来说是一个决战者......
从上表中,结果应为:
UserID | Score1 | Score2 | TotalScore
2 | 0 | 100 | 100
1 | 50 | 10 | 60
3 | 30 | 25 | 55
答案 0 :(得分:4)
SELECT UserID, Score1, Score2, Score1 + Score2 AS "Total"
FROM myTable
ORDER BY Score1 + Score2 DESC
你不需要GROUP BY
,因为它不是一个聚合函数,它只是一个计算列。
您需要在分组后加上最高总分和用户ID。这是一个带有公用表表达式的示例:
WITH maxScores AS (
SELECT UserID AS "id", MAX(Score1 + Score2) AS "total"
FROM scores
GROUP BY UserID
)
SELECT s.UserID, s.Score1, s.Score2, s.Score1 + s.Score2 AS "Total"
FROM scores s
JOIN maxScores m ON s.UserID = m.id
AND s.Score1 + s.Score2 = m.Total
答案 1 :(得分:1)
select UserID, Score1, Score2
from YourTable
order by Score1 + Score2
答案 2 :(得分:1)
你看起来像这样吗?
declare @t table( id int, s1 int, s2 int)
insert into @t (id, s1, s2) values (0, 10, 5)
insert into @t (id, s1, s2) values (1, 50, 15)
insert into @t (id, s1, s2) values (2, 20, 25)
insert into @t (id, s1, s2) values (1, 30, 0)
select id, s1, s2, (s1+s2) as 'total' from @t order by (s1+s2) desc, id asc
1 50 15 65 2 20 25 45 1 30 0 30 0 10 5 15
答案 3 :(得分:1)
那么,这就是你想要的吗?
declare @t table( id int, s1 int, s2 int)
insert into @t (id, s1, s2) values (0, 10, 5)
insert into @t (id, s1, s2) values (1, 50, 15)
insert into @t (id, s1, s2) values (2, 30, 25)
insert into @t (id, s1, s2) values (1, 40, 0)
select id, MAX(s1) max_s1, MAX(s2) max_s2, SUM(total) total from
(select id, s1, s2, (s1+s2) as 'total' from @t) a
group by id
order by total
我担心您在使用相同的s1
对行进行分组后,确实没有说明您要对s2
和id
做什么...
答案 4 :(得分:1)
这个怎么样?
SELECT Q1.UserID, Q1.Score1, Q1.Score2, Q1.Total
FROM (SELECT UserID, Score1, Score2, (Score1+Score2) AS Total
FROM myTable) AS Q1,
(SELECT UserId, Max(Score1 + Score2) As Total FROM myTable GROUP BY UserId) As Q2
WHERE Q1.UserId=Q2.UserId AND Q1.Total=Q2.Total
ORDER BY 4 DESC, 1
答案 5 :(得分:0)
这回答了吗?假设你想要为同一个id包含相同score1 + score2的重复项(如果没有将DENSE_RANK更改为ROW_NUMBER)
create table #data (id int,score1 int, score2 int)
insert into #data Values (0,10,5)
insert into #data Values (1,50,15)
insert into #data Values (2,30,25)
insert into #data Values (1,40,0)
** edit for sorting as per question revision**
;with scores AS
(
SELECT
id
,score1
,score2
,DENSE_RANK() OVER (PARTITION BY id ORDER BY score1 + score2 DESC) AS score_rank
FROM #data
)
SELECT
id
,score1
,score2
,score1 + score2 AS sum_
FROM scores where score_rank = 1
ORDER BY score1 + score2 DESC