oracle:计算一行中的空字段数
我有一个有5个可选字段的表。我想知道有多少行的5个字段全部为空,有多少行的1个字段为非空,等等 我试过几件事,比如:oracle:计算一行中的空字段数,oracle,plsql,null,Oracle,Plsql,Null,我有一个有5个可选字段的表。我想知道有多少行的5个字段全部为空,有多少行的1个字段为非空,等等 我试过几件事,比如: select count(*), ( (if field1 is null then 1 else 0) + (if field2 is null then 1 else 0) + etc. 但这当然行不通 理想情况下,我要寻找的输出是 Nulls Cnt 0 200 1 345 ... 5 40 有优雅的解决方案吗
select
count(*),
( (if field1 is null then 1 else 0) +
(if field2 is null then 1 else 0) +
etc.
但这当然行不通
理想情况下,我要寻找的输出是
Nulls Cnt
0 200
1 345
...
5 40
有优雅的解决方案吗?关键字不是if,而是case,您必须使用端到端case语句
以下是一个适合您的查询:
WITH subQuery AS
(
SELECT My_Table.*, (CASE WHEN My_Table.field1 IS NULL THEN 1 ELSE 0 END +
CASE WHEN My_Table.field2 IS NULL THEN 1 ELSE 0 END +
CASE WHEN My_Table.field3 IS NULL THEN 1 ELSE 0 END +
CASE WHEN My_Table.field4 IS NULL THEN 1 ELSE 0 END +
CASE WHEN My_Table.field5 IS NULL THEN 1 ELSE 0 END ) NumberOfNullFields
FROM My_Table
)
SELECT NumberOfNullFields, COUNT(*)
FROM subQuery
GROUP BY NumberOfNullFields;
虽然在计算时,这个案例没有什么问题,但我只是想看看是否还有其他方法
WITH SAMPLEDATA AS(--just generate some data with nulls for 5 cols
select level ,
(case when mod(level,2) = 0 then 1 else null end) colA,
(case when mod(level,3) = 0 then 1 else null end) colB,
(case when mod(level,5) = 0 then 1 else null end) colC,
(case when mod(level,7) = 0 then 1 else null end) colD,
(case when mod(level,11) = 0 then 1 else null end) colE
from dual
connect by level < 1000
), --utilize the count(Aggregate)'s avoidance of nulls to our summation advantage
nullCols as(
SELECT COUNT(COLA) aNotNull
,cOUNT(*)-COUNT(COLA) aNull
,count(colB) bNotNull
,cOUNT(*)-count(colB) bNull
,count(colc) cNotNull
,cOUNT(*)-count(colc) cNull
,count(cold) dNotNull
,cOUNT(*)-count(cold) dNull
,count(cole) eNotNull
,cOUNT(*)-count(cole) eNull
, cOUNT(*) TotalCountOfRows
from SAMPLEDATA )
SELECT (select count(*) from sampledata where cola is null and colb is null and colc is null and cold is null and cole is null) allIsNull
,nullCols.*
FROM nullCols;
ALLISNULL ANOTNULL ANULL BNOTNULL BNULL CNOTNULL CNULL DNOTNULL DNULL ENOTNULL ENULL TOTALCOUNTOFROWS
---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ---------------------- ----------------------
207 499 500 333 666 199 800 142 857 90 909 999
这利用了
countexpression中的If表达式
计算结果为null,不计算该值:
如从
如上所述,这种方法不能很好地“雄辩地”求和所有空列。只是想看看如果没有案例逻辑,这是否可行