我有一组排名,按组和排名排序:
Group | Rank
------------
A | 1
A | 2
A | 3
A | 4
A | 5
A | 6
B | 1
B | 2
B | 3
B | 4
C | 1
C | 2
C | 3
C | 4
C | 5
D | 1
D | 2
D | 3
D | 4
我希望按组和排名顺序排列组, n每组排名(此处,n = 2):
Group | Rank
------------
A | 1
A | 2
B | 1
B | 2
C | 1
C | 2
D | 1
D | 2
A | 3
A | 4
B | 3
B | 4
C | 3
C | 4
D | 3
D | 4
A | 5
A | 6
C | 5
我已经使用循环和表变量实现了所需的结果(此处粘贴的代码因为我在SQL小提琴中出现了非描述性语法错误):
CREATE TABLE Rankings([Group] NCHAR(1), [Rank] INT)
INSERT Rankings
VALUES
('A',1),
('A',2),
('A',3),
('A',4),
('A',5),
('A',6),
('B',1),
('B',2),
('B',3),
('B',4),
('C',1),
('C',2),
('C',3),
('C',4),
('C',5),
('D',1),
('D',2),
('D',3),
('D',4)
-- input
DECLARE @n INT = 2 --number of group rankings per rotation
-- output
DECLARE @OrderedRankings TABLE([Group] NCHAR(1), Rank INT)
--
-- in-memory rankings.. we will be deleting used rows
DECLARE @RankingsTemp TABLE(GroupIndex INT, [Group] NCHAR(1), Rank INT)
INSERT @RankingsTemp
SELECT
ROW_NUMBER() OVER (PARTITION BY Rank ORDER BY [Group]) - 1 AS GroupIndex,
[Group],
Rank
FROM Rankings
ORDER BY [Group], Rank
-- loop variables
DECLARE @MaxGroupIndex INT = (SELECT MAX(GroupIndex) FROM @RankingsTemp)
DECLARE @RankingCount INT = (SELECT COUNT(*) FROM @RankingsTemp)
DECLARE @i INT
WHILE(@RankingCount > 0)
BEGIN
SET @i = 0;
WHILE(@i <= @MaxGroupIndex)
BEGIN
INSERT INTO @OrderedRankings
([Group], Rank)
SELECT TOP(@n)
[Group],
Rank
FROM @RankingsTemp
WHERE GroupIndex = @i;
WITH T AS (
SELECT TOP(@n) *
FROM @RankingsTemp
WHERE GroupIndex = @i
);
DELETE FROM T
SET @i = @i + 1;
END
SET @RankingCount = (SELECT COUNT(*) FROM @RankingsTemp)
END
SELECT @RankingCount as RankingCount, @MaxGroupIndex as MaxGroupIndex
-- view results
SELECT * FROM @OrderedRankings
如何使用基于集合的方法(无循环,无表变量)实现所需的排序?
我正在使用SQL Server Enterprise 2008 R2。
修改:为了澄清,我需要每组不超过n
行才能连续显示。此查询的目标是在顺序读取时产生排序,相对于排名,提供每个组的相等表示(每次n行)。
答案 0 :(得分:5)
也许是这样...... SQL FIDDLE
Order by
Ceiling(rank*1.0/2), group, rank
上面的工作小提琴(列名略有变化)
更新:被int math烧掉了......现在应该工作。通过乘以1.0将int强制转换为十进制,因此隐式转换不会丢弃我需要使天花板正确舍入的余数。
答案 1 :(得分:1)
假设您的排名数量相对较少,这将有效:
Order by
case when rank <= n then 10
when rank <= 2*n then 20
when rank <= 3*n then 30
when rank <= 4*n then 40
when rank <= 5*n then 50 --more cases here if needed
else 100
end
, group
, rank