我有一个看起来像这样的表
Indiv_id Trip_band Fav1 Fav2 Fav3 Fav4 Fav5
1234 0-90 386568 null null null 568889
5678 91-180 null 889546 887456 856234 null
我想添加另一列,该列计算特定行中的空值的数量,并使输出看起来像这样:
Indiv_id Trip_band Fav1 Fav2 Fav3 Fav4 Fav5 null_count
1234 0-90 386568 null null null 568889 3
5678 91-180 null 889546 887456 856234 null 2
这有可能实现吗?
预先感谢
答案 0 :(得分:2)
您可以通过使用大小写在下面尝试
select t.*,
case when t.col1 is null then 1
else 0 end
+ case when t.col2 is null then 1 else 0 end
+ ........
+ case when coln is null then 1 else 0 end as null_count
from table t
所以您需要像上面的描述方式那样使用所有列名称
答案 1 :(得分:1)
您可以将多个大小写表达式的结果加在一起,每个要检查的列之一:
-- CTE for sample data
with your_table (Indiv_id, Trip_band, Fav1, Fav2, Fav3, Fav4, Fav5 ) as (
select 1234, '0-90', 386568, null, null, null, 568889 from dual
union all
select 5678, '91-180', null, 889546, 887456, 856234, null from dual
)
-- actual query
select t.*,
case when fav1 is null then 1 else 0 end
+ case when fav2 is null then 1 else 0 end
+ case when fav3 is null then 1 else 0 end
+ case when fav4 is null then 1 else 0 end
+ case when fav5 is null then 1 else 0 end
as null_count
from your_table t;
INDIV_ID TRIP_B FAV1 FAV2 FAV3 FAV4 FAV5 NULL_COUNT
---------- ------ ---------- ---------- ---------- ---------- ---------- ----------
1234 0-90 386568 568889 3
5678 91-180 889546 887456 856234 2
或者您可以使用特定于Oracle的nvl2()
function:
select t.*,
nvl2(fav1, 0, 1)
+ nvl2(fav2, 0, 1)
+ nvl2(fav3, 0, 1)
+ nvl2(fav4, 0, 1)
+ nvl2(fav5, 0, 1)
as null_count
from your_table t;
INDIV_ID TRIP_B FAV1 FAV2 FAV3 FAV4 FAV5 NULL_COUNT
---------- ------ ---------- ---------- ---------- ---------- ---------- ----------
1234 0-90 386568 568889 3
5678 91-180 889546 887456 856234 2
但是案例表达对我来说更清楚。
虽然没有内置功能可一次应用于一行中的所有列,但您需要单独检查所有这些列。 (我想您可以取消旋转,计数和向后旋转-但这是很多额外的工作,无论如何您仍然需要列出这些列...)
答案 2 :(得分:0)
在Oracle 12C +中,您可以使用横向联接:
select x.*, c.cnt
from t cross join lateral
(select count(*) as cnt
from (select x.fav1 as fav from dual union all
select x.fav2 from dual union all
select x.fav3 from dual union all
select x.fav4 from dual union all
select x.fav5 from dual union all
) x
where fav is not null
) c;