[英]How to get the next next to last value if previous value is null
I am trying to clean up a table that basically fill up all the empty value from the 1st non-null value. 我正在尝试清理一个表,该表基本上会填充第一个非空值中的所有空值。
The sample table: 样本表:
ID Number Type
1 51280 %
1 A
2 51279 %
2 B
3 50631 %
3 A
3 B
3 C
There is always a number populated for type '%' and if there is other types the record is null. 始终为类型'%'填充一个数字,如果还有其他类型,则记录为空。 I need to fill up all the empty rows within type '%'.
我需要填写类型'%'中的所有空行。
The final table should be like this: 决赛桌应该像这样:
ID Number Type
1 51280 %
1 51280 A
2 51279 %
2 51279 B
3 50631 %
3 50631 A
3 50631 B
3 50631 C
I tried using lag function in sql server. 我尝试在SQL Server中使用滞后函数。
select ID, number, type,
case when number is not null then number
else lag(number) over (order by id) end as new_number
from tbl
order by ID;
It works fine for records only has 1 Type besides '%' Type. 它对于“%”类型之外仅具有1种类型的记录都适用。 For records that have multiple types, such as Id 3 it will only has 1 record filled up.
对于具有多种类型的记录(例如ID 3),将仅填充1条记录。 I know that since lag() only takes the previous value so Type 'B' for ID 3 will only take Number value from Type 'A', while the value for Type 'A' is null.
我知道,由于lag()仅采用先前的值,因此ID 3的类型'B'将仅从类型'A'中获取数字值,而类型'A'的值为null。
Attaching an example result from my code. 附上我的代码的示例结果。
Number Type New_number ID
50201 % 50201 22
NULL COMP 50201 22
50668 % 50668 22
NULL COMP 50668 22
50617 % 50617 22
NULL COMP 50617 22
196794 % 196794 22
NULL COMP 196794 22
1 % 1 22
NULL XO 1 22
NULL COMP NULL 22
As you can see the last record is null but it should be 1 instead. 如您所见,最后一条记录为空,但应改为1。
I also tried using Max() w/o case when condition but the result only takes in the largest number in that particular id. 我也尝试使用Max()不带条件的情况,但结果只包含该特定ID中的最大数字。
Number Type new_number ID
50201 % 51827 22
NULL COMP 51827 22
50668 % 51827 22
NULL COMP 51827 22
50617 % 51827 22
NULL COMP 51827 22
196794 % 51827 22
NULL COMP 51827 22
1 % 51827 22
NULL XO 51827 22
NULL COMP 51827 22
Is there a way to skip all the null values and only take the top 1 value by Type '%' group? 有没有一种方法可以跳过所有空值,而仅按类型'%'组获取前1个值?
You don't need lag()
. 您不需要
lag()
。 Just use max()
: 只需使用
max()
:
select ID, number, type,
max(number) over (partition by id) as new_number
from tbl
order by ID;
Only one value is populated, so you don't even need the NOT NULL
comparison. 只填充一个值,因此您甚至不需要
NOT NULL
比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.