sql - 从 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
我不知道这是否可以实现。
解决方案
使用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。
推荐阅读
- javascript - 在 React 中传递引用数组
- java - 在 2.23.0 版本中,如果没有 CamelContext,则无法创建 Camel DefaultMessage
- javascript - 如何检查字符串是否包含多个单词?
- wso2 - 将存储在 Iterator 中的属性添加为 Iterator 外部的兄弟姐妹
- node.js - 未安装 React-trello 以响应 JS 项目
- django - 跨越多个关系的 Django 数据库查询
- php - 当值为负时,laravel sum 集合忽略
- flutter - Flutter安装问题,如何解决这个问题?
- ios - Apple 帐户中缺少 NSFileProtectionNone
- excel - 在网络驱动器上共享 *.xlam - 调用 subs 和函数