SQL:计算可以具有空值的列

时间:2018-04-15 13:22:28

标签: sql postgresql

所以我有一个查询来检索每个表中的表名和列数。

SELECT Table_Schema, Table_Name, COUNT(*)
FROM Information_Schema.Columns
GROUP BY Table_Schema, Table_Name
HAVING Table_Schema = 'schema';

如何添加此查询可以存储NULL值的列数

2 个答案:

答案 0 :(得分:0)

使用is_nullable列:

SELECT Table_Schema, Table_Name, COUNT(*)
FROM Information_Schema.Columns
WHERE is_nullable = 'YES'
GROUP BY Table_Schema, Table_Name
HAVING Table_Schema = 'schema';

information_schema.columns上的documentation详细描述了该表格,包括可能感兴趣的其他列。

编辑:

如果要将信息添加到现有查询,只需使用条件聚合:

SELECT Table_Schema, Table_Name, COUNT(*), SUM( (is_nullable = 'YES')::int ) as nullable_clumns
FROM Information_Schema.Columns
GROUP BY Table_Schema, Table_Name
HAVING Table_Schema = 'schema';

答案 1 :(得分:0)

您可以向聚合函数添加FILTER条件,以仅计算满足条件的行:

SELECT table_Schema,
       table_Name,
       count(*) AS total_columns,
       count(*) FILTER (WHERE is_nullable = 'YES') AS nullable_columns
FROM information_schema.columns
GROUP BY table_Schema, table_Name
HAVING table_schema = 'schema';