row_number / dense_rank(团体和岛屿)
row_number / dense_rank (Group & Island)
您将在下面找到可以使用的测试数据。我需要的是 dense_rank、rank、row_number 任何函数来获取 "NoRequired" 中的行编号。
我测试了每个等级和 row_number 函数,甚至尝试使用 WITH 语句,但还没有想出解决方案。
我想这里的主要问题是,"rank function" 需要跳过一个序列,一旦它们之间有不同的键值...
DECLARE @data TABLE (ID int IDENTITY(1,1), X int, NoRequired int);
INSERT INTO @data(X, NoRequired)
VALUES (1000,1), (1000,1), (800,2), (600,3), (1000,4), (1000,4), (800,5);
SELECT *
FROM @data;
这是一个 "group and islands" 问题。一种简单的方法是使用滞后和累积和:
select d.*,
sum(case when prev_x = x then 0 else 1 end) over (order by id) as NoRequired
from (select d.*, lag(x) over (order by id) as prev_x
from @data d
) d;
我们的想法是识别值发生变化的行,然后对这些值进行累加。
DECLARE @data TABLE (ID int IDENTITY(1,1), X int, NoRequired int);
INSERT INTO @data(X, NoRequired)
VALUES (1000,1), (1000,1), (800,2), (600,3), (1000,4), (1000,4), (800,5);
SELECT D.ID, D.X, D.NoRequired, MAX(RQ.RN) MyVal FROM @DATA D JOIN
(SELECT D1.ID, ROW_NUMBER() OVER (ORDER BY D1.ID) RN FROM @data D1
LEFT JOIN @data D2
ON D1.ID = D2.Id + 1
AND D1.X = D2.X
WHERE D2.Id IS NULL) RQ
ON RQ.ID <= D.ID
GROUP BY D.ID, D.X, D.NoRequired
ORDER BY D.ID
您将在下面找到可以使用的测试数据。我需要的是 dense_rank、rank、row_number 任何函数来获取 "NoRequired" 中的行编号。 我测试了每个等级和 row_number 函数,甚至尝试使用 WITH 语句,但还没有想出解决方案。
我想这里的主要问题是,"rank function" 需要跳过一个序列,一旦它们之间有不同的键值...
DECLARE @data TABLE (ID int IDENTITY(1,1), X int, NoRequired int);
INSERT INTO @data(X, NoRequired)
VALUES (1000,1), (1000,1), (800,2), (600,3), (1000,4), (1000,4), (800,5);
SELECT *
FROM @data;
这是一个 "group and islands" 问题。一种简单的方法是使用滞后和累积和:
select d.*,
sum(case when prev_x = x then 0 else 1 end) over (order by id) as NoRequired
from (select d.*, lag(x) over (order by id) as prev_x
from @data d
) d;
我们的想法是识别值发生变化的行,然后对这些值进行累加。
DECLARE @data TABLE (ID int IDENTITY(1,1), X int, NoRequired int);
INSERT INTO @data(X, NoRequired)
VALUES (1000,1), (1000,1), (800,2), (600,3), (1000,4), (1000,4), (800,5);
SELECT D.ID, D.X, D.NoRequired, MAX(RQ.RN) MyVal FROM @DATA D JOIN
(SELECT D1.ID, ROW_NUMBER() OVER (ORDER BY D1.ID) RN FROM @data D1
LEFT JOIN @data D2
ON D1.ID = D2.Id + 1
AND D1.X = D2.X
WHERE D2.Id IS NULL) RQ
ON RQ.ID <= D.ID
GROUP BY D.ID, D.X, D.NoRequired
ORDER BY D.ID