简体   繁体   中英

Auto increment the column value by 1 conditionally in select query in sql

I am having input table like below:

and in a select query without alteration of table need an output like:

drop table if exists T;
create table T(id int, nm nvarchar(10)) 
GO
insert T(id, nm) values (1,'r'),(2,'r'),(3,null),(4,'r')
SELECT * FROM T
GO
-- solution:
select 
    id, nm, 
    CASE WHEN nm is not null then count(nm) over (order by id) ELSE NULL END
from T
GO

compare execution plan of all solutions (using SQL 2017) :-)

My solution 21%; LukStorms solution 38%; Ian-Fogelman solution 41%

Choose your solution after you test in your specific server! 在此输入图像描述

You can calculate a row_number partitioned on whether "nm" is null, then only show the calculated row_number when "nm" is not null.

Example snippet:

declare @T table (id int identity(1,1) primary key, nm varchar(8));
insert into @T (nm) values ('R'),('R'),(null),('R');

select *, 
 iif(nm is null,null,row_number() over (partition by iif(nm is null,1,0) order by id)) as [Count]
from @T
order by id
;WITH CTE AS 
(
    SELECT ID,
           ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY ID) AS [COUNT] 
    FROM [TABLE] WHERE NM IS NOT NULL 
)
SELECT S.ID,
       S.NM,
       CTE.[COUNT] 
FROM [TABLE] AS S LEFT JOIN CTE AS CTE ON S.ID = CTE.ID

在此输入图像描述

You can start with a CTE that adds a ROW_NUMBER() column and filters out rows WHERE 'nm' IS NULL.

Then SELECT from your table and OUTER JOIN to the CTE, using the ROW_NUMBER column to populate your Count column.

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