Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 在一列中具有多个不同属性的查询_.net_Sql_Sql Server - Fatal编程技术网

.net 在一列中具有多个不同属性的查询

.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 我可以得

我正在尝试对表中的一列编写查询。在“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语句的值,但最后一个带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

您希望文本为空您希望文本为空