简体   繁体   English

在sql中的select查询中有条件地自动将列值递增1

[英]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) :-) 比较所有解决方案的执行计划(使用SQL 2017):-)

My solution 21%; 我的解决方案21%; LukStorms solution 38%; LukStorms解决方案38%; Ian-Fogelman solution 41% Ian-Fogelman解决方案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. 您可以计算row_number,分区是否“nm”为空,然后仅在“nm”不为空时显示计算的row_number。

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. 您可以从添加ROW_NUMBER()列的CTE开始,并过滤掉WHERE'nm'为空的行。

Then SELECT from your table and OUTER JOIN to the CTE, using the ROW_NUMBER column to populate your Count column. 然后使用ROW_NUMBER列填充Count列,从表中选择SELECT并使用OUTER JOIN连接到CTE。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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