如何计算 oracle sql 中 table 的所有列中零的数量

How can I count the number of zeros in all columns for a table in oracle sql

假设您有一个名为 db_table1 的数据库 table,其中包含数百列,其中大部分包含很多 0。

我正在尝试计算每一列的零,并将其除以列的长度,这样我就可以看到每一列中零的比率。

下面的代码给出了每列中空值的比率。但我无法修改它来计算 0 而不是空值

任何帮助将不胜感激

SELECT column_name, (num_nulls/ (SELECT COUNT(*) FROM db_table)*100)
FROM all_tab_columns 
WHERE table_name='table’

示例数据:

col_1 col_2 col_3
0.000 0.000 0.000
0.000 0.000 14.857
3.548 0.000 0.000
0.000 0.000 0.000
0.000 0.000 0.000
0.000 11.586 0.000

预期输出:

All_Columns Ratio_of_Zeros
col_1 65.5
col_2 73.5
col_3 48.6

简而言之,我需要每列中零的总数除以总行数,得到每列中零的百分比或比率,这样我就可以将零视为空值,并在列数超过 60 时消除该列零百分比可以说...

您可以使用:

SELECT 'SELECT ''' || table_name || ''' AS table_name, ' ||
               '''' || column_name || ''' AS column_name, ' ||
               '100 - SUM(LENGTH(REPLACE(TO_CHAR("'|| column_name || '", ''fm999999999999999990.000''), ''0''))-1)' ||
               ' / SUM(LENGTH(TO_CHAR("'|| column_name || '", ''fm999999999999999990.000''))-1) * 100 AS ratio_of_zeroes ' ||
       'FROM "' || table_name || '" UNION ALL'
       column_name
FROM   user_tab_columns
WHERE  data_type = 'NUMBER';

生成SQL语句,去掉最后一行的UNION ALL并执行。

如果你有 table:

CREATE TABLE table_name (col_1, col_2, col_3) AS
SELECT 0.000,  0.000,  0.000 FROM DUAL UNION ALL
SELECT 0.000,  0.000, 14.857 FROM DUAL UNION ALL
SELECT 3.548,  0.000,  0.000 FROM DUAL UNION ALL
SELECT 0.000,  0.000,  0.000 FROM DUAL UNION ALL
SELECT 0.000,  0.000,  0.000 FROM DUAL UNION ALL
SELECT 0.000, 11.586,  0.000 FROM DUAL;

那么生成的语句(去掉最后的UNION ALL)是:

SELECT 'TABLE_NAME' AS table_name, 'COL_1' AS column_name, 100 - SUM(LENGTH(REPLACE(TO_CHAR("COL_1", 'fm999999999999999990.000'), '0'))-1) / SUM(LENGTH(TO_CHAR("COL_1", 'fm999999999999999990.000'))-1) * 100 AS ratio_of_zeroes FROM "TABLE_NAME" UNION ALL
SELECT 'TABLE_NAME' AS table_name, 'COL_2' AS column_name, 100 - SUM(LENGTH(REPLACE(TO_CHAR("COL_2", 'fm999999999999999990.000'), '0'))-1) / SUM(LENGTH(TO_CHAR("COL_2", 'fm999999999999999990.000'))-1) * 100 AS ratio_of_zeroes FROM "TABLE_NAME" UNION ALL
SELECT 'TABLE_NAME' AS table_name, 'COL_3' AS column_name, 100 - SUM(LENGTH(REPLACE(TO_CHAR("COL_3", 'fm999999999999999990.000'), '0'))-1) / SUM(LENGTH(TO_CHAR("COL_3", 'fm999999999999999990.000'))-1) * 100 AS ratio_of_zeroes FROM "TABLE_NAME";

执行的输出是:

TABLE_NAME COLUMN_NAME RATIO_OF_ZEROES
TABLE_NAME COL_1 83.33333333333333333333333333333333333333
TABLE_NAME COL_2 80
TABLE_NAME COL_3 80

db<>fiddle here

您可以使用:


WITH AA AS (
select 
col_1,col_2,col_3
from table_name
)

SELECT column_name, COUNT(column_name) zeros FROM
(
SELECT * FROM (

SELECT * FROM AA
UNPIVOT(
    zeros  
    FOR column_name 
    IN ( 
col_1,col_2,col_3
    )
)
) WHERE zeros = 0
) GROUP BY column_name