当列值更改时,我一直在尝试重置row_number,我不知道该怎么做。
这是我的SQL代码段:
['posts/(?P<id>[0-9]+)/delete/$']
基于数据集,我尝试每次将每个主题的值更改时将FrequencyCounter重置为1,现在它执行我想要的50%,在找到值1或2时进行计数,但是当值1在值2之后再次出现时,它将从其剩余位置继续计数。我希望每次值更改时,计数也要从头开始。
答案 0 :(得分:3)
没有示例数据很难复制和测试,但是如果您想知道如何根据列值的变化对行进行编号,那么下一种方法可能会有所帮助。它可能不是最好的,但至少会给您一个良好的开端。当然,希望我能正确理解您的问题。
数据:
CREATE TABLE #Data (
[Id] int,
[Subject] varchar(3),
[Value] int
)
INSERT INTO #Data
([Id], [Subject], [Value])
VALUES
(1, '801', 1),
(2, '801', 2),
(3, '801', 2),
(4, '801', 2),
(5, '801', 1),
(6, '801', 2),
(7, '801', 2),
(8, '801', 2)
声明:
;WITH ChangesCTE AS (
SELECT
*,
CASE
WHEN LAG([Value]) OVER (PARTITION BY [Subject] ORDER BY [Id]) <> [Value] THEN 1
ELSE 0
END AS [Change]
FROM #Data
), GroupsCTE AS (
SELECT
*,
SUM([Change]) OVER (PARTITION BY [Subject] ORDER BY [Id]) AS [GroupID]
FROM ChangesCTE
)
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY [GroupID] ORDER BY [Id]) AS Rn
FROM GroupsCTE
结果:
--------------------------------------
Id Subject Value Change GroupID Rn
--------------------------------------
1 801 1 0 0 1
2 801 2 1 1 1
3 801 2 0 1 2
4 801 2 0 1 3
5 801 1 1 2 1
6 801 2 1 3 1
7 801 2 0 3 2
8 801 2 0 3 3
答案 1 :(得分:0)
据我了解,您需要DENSE_RANK,因为您要查找的行号仅在值更改时才会更改。语法如下-
WITH your_table(your_column)
AS
(
SELECT 2 UNION ALL
SELECT 10 UNION ALL
SELECT 2 UNION ALL
SELECT 11
)
SELECT *,DENSE_RANK() OVER (ORDER BY your_column)
FROM your_table