.net 在一列中具有多个不同属性的查询
我正在尝试对表中的一列编写查询。在“text”列中,我可以有5或10或null的值。我想得到表中5行、10行或null行的计数。我写了下面的查询,它工作不正常.net 在一列中具有多个不同属性的查询,.net,sql,sql-server,.net,Sql,Sql Server,我正在尝试对表中的一列编写查询。在“text”列中,我可以有5或10或null的值。我想得到表中5行、10行或null行的计数。我写了下面的查询,它工作不正常 select COUNT(*) from t_test select COUNT(text) from t_test where text=5 select COUNT(text) from t_test where text=10 select COUNT(text) from t_test where text=null 我可以得
select COUNT(*) from t_test
select COUNT(text) from t_test where text=5
select COUNT(text) from t_test where text=10
select COUNT(text) from t_test where text=null
我可以得到前三个select语句的值,但最后一个带null的语句返回零,而其中有带null的行。如何编写此查询?谢谢您应该只使用条件求和:
select count(*),
sum(case when text = '5' then 1 else 0 end) as Num_5,
sum(case when text = '10' then 1 else 0 end) as Num_10,
sum(case when text is null then 1 else 0 end) as Num_Null
from t_test;
这是假设一个名为text
的字段存储为字符串,因此常量被放在引号中。如果它真的是一个数字,首先我想知道为什么它被称为text
。在这种情况下,您可以省去单引号
在您的例子中,最后一个不起作用,因为count(text)
计算非空值。但是where
子句只保留NULL
值。对于这个问题,您应该使用count(*)
。正确的查询是:
select count(*) from t_test where text is null;
您应该只使用条件求和:
select count(*),
sum(case when text = '5' then 1 else 0 end) as Num_5,
sum(case when text = '10' then 1 else 0 end) as Num_10,
sum(case when text is null then 1 else 0 end) as Num_Null
from t_test;
这是假设一个名为text
的字段存储为字符串,因此常量被放在引号中。如果它真的是一个数字,首先我想知道为什么它被称为text
。在这种情况下,您可以省去单引号
在您的例子中,最后一个不起作用,因为count(text)
计算非空值。但是where
子句只保留NULL
值。对于这个问题,您应该使用count(*)
。正确的查询是:
select count(*) from t_test where text is null;
最终查询所需的是:
select COUNT(*) from t_test where text is null
注意:
而不是COUNT(*)
为空,不呈现任何值COUNT(TEXT)
而不是为null
=null
select COUNT(*) from t_test
select COUNT(text) from t_test where text=5
select COUNT(text) from t_test where text=10
select COUNT(*) from t_test where text is null
最终查询所需的是:
select COUNT(*) from t_test where text is null
注意:
而不是COUNT(*)
为空,不呈现任何值COUNT(TEXT)
而不是为null
=null
select COUNT(*) from t_test
select COUNT(text) from t_test where text=5
select COUNT(text) from t_test where text=10
select COUNT(*) from t_test where text is null
您希望文本为空您希望文本为空