如何检查值是否为NULL,然后选择每个PolicyNumber不为null的值。 SQL Server 2012

时间:2018-04-17 15:46:57

标签: sql sql-server tsql

对于PolicyNumber ENV1,如果PolicyType为NULL,那么我需要选择非空的,即“Primary”。

与策略ENV3相同:ID 005具有空值,因此对于PolicyNumber ENV3,它应该是'Claim Made'

需要接下来的非空值

有没有办法在没有分组的情况下实现这一目标?

declare @TestTable table 
                   (
                       ID int,  
                       PolicyNumber varchar(50), 
                       PolicyType varchar(50)
                   )

insert into @TestTable 
values (001, 'ENV1','Primary'), (002, 'ENV1',NULL),
       (003, 'ENV2','Claim Made'), (004, 'ENV3','Claim Made'),
       (005, 'ENV3',NULL)

select 
    ID,  
    PolicyNumber, 
    PolicyType
from
    @TestTable

输出:

ID  PolicyNumber    PolicyType
-------------------------------
1   ENV1            Primary
2   ENV1            NULL
3   ENV2            Claim Made
4   ENV3            Claim Made
5   ENV3            NULL

2 个答案:

答案 0 :(得分:1)

使用LAG

declare @TestTable table (ID int,  PolicyNumber varchar(50), PolicyType varchar(50))
insert into @TestTable values 
                       (001, 'ENV1','Primary'),
                       (002, 'ENV1',NULL),
                       (003, 'ENV2','Claim Made'),
                       (004, 'ENV3','Claim Made'),
                       (005, 'ENV3',NULL)

select  ID,  
        PolicyNumber, 
        PolicyType = case when PolicyType is null then lag(PolicyType) over (partition by PolicyNumber order by ID) else PolicyType end
from @TestTable

当然,如果有连续的NULL值,我们可以通过几种方式处理这个问题。这是一个:

declare @TestTable table (ID int,  PolicyNumber varchar(50), PolicyType varchar(50))
insert into @TestTable values 
                       (001, 'ENV1','Primary'),
                       (002, 'ENV1',NULL),
                       (003, 'ENV2','Claim Made'),
                       (004, 'ENV3','Claim Made'),
                       (005, 'ENV3',NULL),
                       (006, 'ENV3',NULL)

select  t.ID,  
        t.PolicyNumber, 
        PolicyType = case when t.PolicyType is null then (select top 1 PolicyType 
                                                          from @TestTable 
                                                          where PolicyType is not null 
                                                               and PolicyNumber = t.PolicyNumber
                                                          order by ID desc) 
                         else PolicyType end
from @TestTable t

答案 1 :(得分:0)

我会使用窗口函数来执行此操作:

select t.*,
       coalesce(policy_number,
                max(policynumber) over (partition by id)
               ) as new_policy_number
from t;