我有如下输入表:
在不更改表的情况下,
和在选择查询中需要类似以下的输出:
答案 0 :(得分:4)
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
比较所有解决方案的执行计划(使用SQL 2017):-)
我的解决方案为21%; LukStorms解决方案38%; Ian-Fogelman解决方案41%
答案 1 :(得分:3)
您可以根据“ nm”是否为空来计算行号,然后仅在“ nm”不为空时显示计算出的行号。
示例代码段:
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
答案 2 :(得分:1)
;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
答案 3 :(得分:0)
您可以从CTE开始,该CTE添加ROW_NUMBER()列并过滤出“ nm”为NULL的行。
然后使用ROW_NUMBER列填充Count
列,然后从表中进行SELECT并从OUTER JOIN到CTE。