好的,所以,让我们假装我有一张这样的桌子:
Name Rank Score
Adam 1 10
Adam 2 20
Adam 3 14
Jane 2 11
Jane 3 14
Jane 4 45
Rick 1 49
Rick 3 24
Rick 5 12
我需要在单个表中生成一组结果,其中SUMs在一列中排名1和2,在第二列中排名3+。我可以将它作为两个单独的SQL语句来执行,如下所示:
SELECT Name, SUM(Score) AS Score1
FROM Table
WHERE Rank < 3
GROUP BY Name
和
SELECT Name, SUM(Score) AS Score2
FROM Table
WHERE Rank > 2
GROUP BY Name
但我无法想出任何方法来生成一个导致单个表的SQL语句,可能如下所示:
Name Score1 Score2
Adam 30 14
Jane 11 59
Rick 49 36
感谢任何帮助。谢谢!
答案 0 :(得分:5)
这假设Ranks
是整数:
SELECT Name,
sum(case when Rank in (1, 2) then Score else null end) as Score1,
sum(case when Rank < 1 or Rank > 2 then Score else null end) as Score2
FROM Table
GROUP BY Name