仅当特定列的值= 1时,SQL Row_Number()才会增加

时间:2017-11-16 05:47:45

标签: sql sql-server sql-server-2008

我在SQL查询中生成row_number()时遇到了一些麻烦。我有以下输出的查询 -

enter image description here

现在,我想为所有行添加行号,其中行号仅在C1中的值为1时增加。所需输出如下 -

My Required Output

任何帮助将不胜感激。 TIA

3 个答案:

答案 0 :(得分:1)

表变量:

DECLARE @Table AS TABLE (C1 INT)
INSERT INTO @Table VALUES (1),(4),(1),(1),(4),(1),(3),(4)

SQL 2008版本

;WITH cteSimulateAnOriginalIdentityKey AS (
    SELECT
       C1
       ,OriginalOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       @Table
)

, cteC1RowNumber AS (
    SELECT
       *
       ,C1RowNumber = ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY OriginalOrder)
    FROM
       cteSimulateAnOriginalIdentityKey
)

SELECT
    C1
    ,RN = ISNULL((SELECT MAX(C1RowNumber) FROM cteC1RowNumber r2 WHERE r2.C1 = 1 AND r2.OriginalOrder <= r1.OriginalOrder),1)
FROM
    cteC1RowNumber r1
ORDER BY
    OriginalOrder

SQL 2012+版

;WITH cteSimulateAnOriginalIdentityKey AS (
    SELECT
       C1
       ,OriginalOrder = ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM
       @Table
)

, cteC1RowNumber AS (
    SELECT
       *
       ,C1RowNumber = ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY OriginalOrder)
    FROM
       cteSimulateAnOriginalIdentityKey
)

SELECT
    C1
   ,RN = ISNULL(MAX(CASE WHEN C1 = 1 THEN C1RowNumber END) OVER (ORDER BY OriginalOrder),1)
FROM
    cteC1RowNumber
ORDER BY
    OriginalOrder

结果:

C1  RN
1   1
4   1
1   2
1   3
4   3
1   4
3   4
4   4

如果您实际上有另一列用于维护所需的原始订单,则您不需要第一个只是模拟该列的cte

答案 1 :(得分:0)

试试这个:

SELECT C1,
       ROW_NUMBER() OVER (PARTITION BY C1 ORDER BY (SELECT 100)) RN
FROM TableNAme

答案 2 :(得分:0)

我假设您在查询中有另一列用于确定行的顺序;没有这样的标准,你的整个问题毫无意义。

以下查询适用于SQL Server 2012或更高版本:

declare @Table table (
    Id int identity(1,1) not null,
    C1 int
);

insert into @Table(C1) values (1),(4),(1),(1),(4),(1),(3),(4);

select t.C1,
    sum(case t.C1 when 1 then 1 else 0 end) over(order by t.Id) as [RN]
from @Table t;