序列号1中的字段为Null返回字段在序列号2中

时间:2018-08-10 23:49:57

标签: sql null db2 isnull seq

我最初在where语句中放置了seq1(最近的物理地址)将是我想要的,但是如果它是LIKE(“ SEE%”),则提供邮件地址。但是,我注意到在某些情况下会显示“ See Mailing”,然后邮件中为空。发生这种情况时,我想返回序列2的邮寄地址。我在下面提供了一个示例,说明正在发生什么以及将要发生什么。

样本数据:

Cust_ID  SeqNum PhysicalAddress  MailingAddress
1          1        1 Main St     PO Box 1
1          2        1 Main St     PO Box 1
1          3        1 First Ave   PO Box 1
2          1        See Mailing     Null
2          2        See Mailing   2 Main St
2          3        See Mailing   2 Main St
3          1        See Mailing   3 Main St
3          2        3 Main St     3 Main St
3          3        3 Third St    3 Third St

所需结果:

Cust_ID  SeqNum      Address
1           1       1 Main St
2           2       2 Main St
3           1       3 Main St

请帮助我找出构建此查询的最佳方法。我应该在SELECT子句中建立一个案例还是在WHERE子句中组合AND和OR?

2 个答案:

答案 0 :(得分:0)

怎么样?

SELECT  "Cust_ID"
,       "SeqNum"
,       CASE WHEN "PhysicalAddress" = 'See Mailing' THEN "MailingAddress" ELSE "PhysicalAddress" END AS "Address"
FROM
(
    SELECT T.*, ROW_NUMBER() OVER(PARTITION BY "Cust_Id" ORDER BY "SeqNum") AS "RowNum"
    FROM   "Table" T
    WHERE  "MailingAddress" IS NOT NULL
    OR     "PhysicalAddress" <> 'See Mailing'
)
WHERE "RowNum" = 1

答案 1 :(得分:0)

其他方法(如果只有一行具有空地址,请不要删除ID)

select * from (
    select f1.*,  
    rownumber() over(partition by f1.Cust_ID 
    order by case when (case when f1.PhysicalAddress='See Mailing' then f1.MailingAddress else f1.PhysicalAddress end) is null then cast(null as integer) else SeqNum  end)  rang 
    from FormatedAdresse f1
) tmp where rang=1