处理 SQL Server 2012 SELECT 语句中丢失的数据
Handle missing data in SQL Server 2012 SELECT statement
create table t1 (col1 int);
将 table 留空。
select isnull(col1,0) from t1;
我想在上面的例子中用零替换空值。但是,如果 table 中没有记录,ISNULL()
将不起作用。我该如何解决这个问题?
如果 table 中不存在任何记录,则您的查询 returns EMPTY not NULL 。
您可以将 EMPTY 值转换为 NULL 值,然后将其切换为 0,如下所示:
SELECT ISNULL((SELECT col1 FROM tl),0) AS col1;
如果您绝对必须为空 table 返回一个值,可能类似于:
if ((select COUNT(*) from t1) = 0)
begin
select 0 as col1;
end
else
begin
select isnull(col1,0) as col1 from t1;
end
如果你想替换不存在的值,那么围绕提到的 select 语句的另一个空检查。像这样
ISNULL(select isnull(col1,0) from t1,0)
COALESCE(col1, 0)
将为您提供列表中的第一个非 NULL 值,即
col1
如果 col1
不包含 NULL
0
如果 col1
包含 NULL
.
也许你可以先测试一下 table 是否为空:
IF NOT EXISTS (select * from t1)
SELECT 0
ELSE select coalesce(col1,0) from t1;
无论如何,您应该使用 COALESCE 而不是 ISNULL,因为它是标准的 SQL。
当我想 return 恰好 来自 table 的一行可能是空的或有任意行数时,我经常使用聚合:
select coalesce(max(col1), 0)
from t1;
保证 return 恰好一行。但是,当 table 不为空时,不清楚您想要什么。
left join
将获得硬编码 table、OneZero
,即使 t1
.
中没有行
select isnull(t1.col1, OneZero.zero)
from ( values(0) ) as OneZero (zero)
left join t1
on 1 = 1
create table t1 (col1 int);
将 table 留空。
select isnull(col1,0) from t1;
我想在上面的例子中用零替换空值。但是,如果 table 中没有记录,ISNULL()
将不起作用。我该如何解决这个问题?
如果 table 中不存在任何记录,则您的查询 returns EMPTY not NULL 。 您可以将 EMPTY 值转换为 NULL 值,然后将其切换为 0,如下所示:
SELECT ISNULL((SELECT col1 FROM tl),0) AS col1;
如果您绝对必须为空 table 返回一个值,可能类似于:
if ((select COUNT(*) from t1) = 0)
begin
select 0 as col1;
end
else
begin
select isnull(col1,0) as col1 from t1;
end
如果你想替换不存在的值,那么围绕提到的 select 语句的另一个空检查。像这样
ISNULL(select isnull(col1,0) from t1,0)
COALESCE(col1, 0)
将为您提供列表中的第一个非 NULL 值,即
col1
如果col1
不包含NULL
0
如果col1
包含NULL
.
也许你可以先测试一下 table 是否为空:
IF NOT EXISTS (select * from t1)
SELECT 0
ELSE select coalesce(col1,0) from t1;
无论如何,您应该使用 COALESCE 而不是 ISNULL,因为它是标准的 SQL。
当我想 return 恰好 来自 table 的一行可能是空的或有任意行数时,我经常使用聚合:
select coalesce(max(col1), 0)
from t1;
保证 return 恰好一行。但是,当 table 不为空时,不清楚您想要什么。
left join
将获得硬编码 table、OneZero
,即使 t1
.
select isnull(t1.col1, OneZero.zero)
from ( values(0) ) as OneZero (zero)
left join t1
on 1 = 1