Photo of Sample Data in blue我有这种格式的数据。我需要为每组非缺失值找到缺失。或者,如果我可以创建一个列来计算SQL Server中不丢失元素的组。
MOB ID Column1 Column2
0 123 Null Null
1 123 Null Null
2 123 25 25
3 123 36 25
4 123 Null Null
5 123 Null Null
6 123 Null Null
7 123 15 15
8 123 23 15
9 123 24 15
10 123 41 15
11 123 Null Null
12 123 Null Null
13 123 Null Null
14 123 Null Null
15 123 Null Null
16 123 Null Null
17 123 Null Null
18 123 77 77
19 123 Null Null
20 123 Null Null
21 123 Null Null
22 123 22 22
23 123 35 22
24 123 38 22
在上面的示例中,前三列代表表中的列。第四列(Column2
)是我想在SELECT语句中生成的一个人造列,它基于从{{1}中的每个“岛”中的NON-NULL值中获取Column1
的最小值}。
答案 0 :(得分:0)
在这里使用我的水晶球(快到圣诞节了,所以也许应该是雪球),但是,也许这就是您想要的:
WITH VTE AS(
SELECT *
FROM (VALUES(0 ,123,NULL),
(1 ,123,NULL),
(2 ,123,25 ),
(3 ,123,36 ),
(4 ,123,NULL),
(5 ,123,NULL),
(6 ,123,NULL),
(7 ,123,15 ),
(8 ,123,23 ),
(9 ,123,24 ),
(10,123,41 ),
(11,123,NULL),
(12,123,NULL),
(13,123,NULL),
(14,123,NULL),
(15,123,NULL),
(16,123,NULL),
(17,123,NULL),
(18,123,77 ),
(19,123,NULL),
(20,123,NULL),
(21,123,NULL),
(22,123,22 ),
(23,123,35 ),
(24,123,38 )) V(MOB,ID,Column1)),
Islands AS(
SELECT MOB,
ID,
Column1,
CASE WHEN Column1 IS NULL THEN 0 ELSE 1 END AS Gap,
ROW_NUMBER() OVER (ORDER BY MOB) -
ROW_NUMBER() OVER (PARTITION BY CASE WHEN Column1 IS NULL THEN 0 ELSE 1 END ORDER BY MOB) AS Island
FROM VTE)
SELECT MOB,
ID,
Column1,
MIN(Column1) OVER (PARTITION BY Gap, Island) AS Column2
FROM Islands
ORDER BY MOB;