简体   繁体   中英

SQL Row_Number() increase only when the value = 1 for a specific column

I am having some trouble generating row_number() in my SQL query as my expectation. I have this following output of my query-

在此处输入图片说明

Now, I want to add row number for all rows where row number will only increase when the value in C1 is = 1. Required output as below-

我需要的输出

Any help will be appreciated. TIA

Table Variable:

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

SQL 2008 Version

;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+ version

;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

RESULT:

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

If you in fact have another column by which to maintain the desired original order you don't need the first cte which is simply simulating that column

Try this:

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

I presume you have another column(s) in your query by which you determine the order of rows; without such a criteria, your whole question is pointless.

The query below will work on SQL Server 2012 or later versions:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM