首页 > 解决方案 > 从 20+ 列 sql 中选择 3 个非空值

问题描述

我有一个包含生物信息的表格和 20 + 列不同类型的电话号码,所有列名称都不同(电子邮件和地址相同)我试图通过从每个列中选择前 3 个非空值来清理表格排。

现在我有

Id   FN     LN    Gender phone1    phone2   phone3   cellphone cell1 cell2    cell3  cell4  business1 etc
234  John  Smith  F     123-4566  Null     763-2899  243-8299  Null  289-2389  Null  Null   Null etc
394  Jane  Smith  F     Null      232-3553 345-2453  Null      Null  Null      Null  Null    453-5656 etc
556  Dash  Doe    M     121-3233  234-5466 234-2556  356-3564  232-6766 453-3453 676-2354  435-4543  etc

我想得到输出

Id   FN     LN    Gender phone1    phone2     phone3  
234  John  Smith  F     123-456    763-2899    243-8299  
394  Jane  Smith  F     232-3553   345-2453    453-5656
556  Dash  Doe    M     121-3233   234-5466     234-2556  

我不知道这是否可以实现。

标签: sqlsql-server

解决方案


使用cross apply和条件聚合:

select t.*, p.*
from t cross apply
     (select max(case when seqnum = 1 then p.phone end) as phone1,
             max(case when seqnum = 2 then p.phone end) as phone2,
             max(case when seqnum = 3 then p.phone end) as phone3
      from (select v.phone, row_number() over (order by v.ord) as seqnum
            from (values (1, t.phone1), (2, t.phone2), (3, t.phone3),
                         (4, t.cellphone), . . .
                 ) v(ord, phone)
            where phone is not null
           ) p
     ) p

是一个 db<>fiddle。


推荐阅读