我试图通过对sid进行分组并通过SQL Server中的标记对组进行排名来对下表进行排名。
请参阅下表并回答问题:
标记:
sid sub marks
----------------------
53666 sub1 30
53666 sub2 15
53666 sub2 20
53667 sub1 10
53667 sub2 40
53667 sub3 20
使用开窗/分析功能可以查询以下输出:
sid sub rank
---------------------
53666 sub1 1
53666 sub2 3
53666 sub2 2
53667 sub1 3
53667 sub2 1
53667 sub3 2
答案 0 :(得分:2)
尝试此查询
SELECT *, CASE
WHEN mark >= 30 THEN 1
WHEN mark <= 15 THEN 3
ELSE 2
END
FROM [dbo].[Q1]
输出
id sid sub mark
----------- ----------- ---------- ----------- -----------
1 53666 sub1 30 1
2 53666 sub2 15 3
3 53666 sub2 20 2
4 53667 sub1 10 3
5 53667 sub2 40 1
6 53667 sub3 20 2
答案 1 :(得分:0)
您可以尝试使用带有适当的SUM()
和PARTITION BY
子句的窗口ORDER BY
:
表格:
CREATE TABLE Marks (
sid int,
sub varchar(4),
marks int
)
INSERT INTO Marks
(sid, sub, marks)
VALUES
(53666, 'sub1', 30),
(53666, 'sub2', 15),
(53666, 'sub2', 20),
(53667, 'sub1', 10),
(53667, 'sub2', 40),
(53667, 'sub3', 20)
声明:
SELECT
sid, sub, SUM(1) OVER (PARTITION BY sid ORDER BY marks DESC) AS rn
FROM Marks
ORDER BY sid, sub, marks
结果:
------------------
sid sub rn
------------------
53666 sub1 1
53666 sub2 3
53666 sub2 2
53667 sub1 3
53667 sub2 1
53667 sub3 2