Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.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
SQL Server查询以计算列中的负值和正值数(分组依据)_Sql_Sql Server - Fatal编程技术网

SQL Server查询以计算列中的负值和正值数(分组依据)

SQL Server查询以计算列中的负值和正值数(分组依据),sql,sql-server,Sql,Sql Server,你能帮我计算下表余额列中正负值的SQL查询吗。非常感谢您的帮助 我使用了以下查询,但它没有组合结果 select ACCT_GROUP + ' account has ' + cast (count(distinct Balance) as nvarchar(20)) + ' Negative Values' from #tmptrueup where Balance<0 group by ACCT_GROUP union select ACCT_GROUP + ' account h

你能帮我计算下表余额列中正负值的SQL查询吗。非常感谢您的帮助

我使用了以下查询,但它没有组合结果

select  ACCT_GROUP + ' account has ' + cast (count(distinct Balance) as nvarchar(20)) + ' Negative Values' from #tmptrueup where Balance<0 group by ACCT_GROUP
union
select  ACCT_GROUP + ' account has ' + cast (count(distinct Balance) as nvarchar(20)) + ' Positive Values' from #tmptrueup where Balance>0 group by ACCT_GROUP
您可以为此使用条件聚合:

select  ACCT_GROUP + ' account has ' + 
        cast (count(case when Balance < 0 then 1 end) as nvarchar(20)) + 
        ' Negative Values and ' +
        cast (count(case when Balance >= 0 then 1 end) as nvarchar(20)) +
         ' positive.'
from #tmptrueup 
group by ACCT_GROUP
注意:如果要计算不同的值,则可以使用:

count(distinct case when Balance < 0 then Balance end)
代替

count(case when Balance < 0 then 1 end)
并对正值执行相同的操作。

您可以使用条件聚合:

select  ACCT_GROUP + ' account has ' + 
        cast (count(case when Balance < 0 then 1 end) as nvarchar(20)) + 
        ' Negative Values and ' +
        cast (count(case when Balance >= 0 then 1 end) as nvarchar(20)) +
         ' positive.'
from #tmptrueup 
group by ACCT_GROUP
注意:如果要计算不同的值,则可以使用:

count(distinct case when Balance < 0 then Balance end)
代替

count(case when Balance < 0 then 1 end)

对于正值也要做同样的事情。

您需要在小组中设置一个案例

select ACCT_GROUP
, SUM(case when Balance < 0 then 1 else 0 end) as NegativeCount
, SUM(case when Balance >= 0 then 1 else 0 end) as PositiveCount
from #tmptrueup
group by 
    case 
        when Balance < 0 then 1 
        else 0 
    end

你需要一个小组的案例

select ACCT_GROUP
, SUM(case when Balance < 0 then 1 else 0 end) as NegativeCount
, SUM(case when Balance >= 0 then 1 else 0 end) as PositiveCount
from #tmptrueup
group by 
    case 
        when Balance < 0 then 1 
        else 0 
    end

请编辑文章以包含文本格式的样本数据。请编辑文章以包含文本格式的样本数据。您不需要使用SUM而不是count吗?行数不会根据大小写表达式更改。或者在您的case表达式中删除else,这样就不会计算空值。您不需要使用SUM而不是count吗?行数不会根据大小写表达式更改。或者在你的case表达式中去掉else,这样空值就不会被计算了。非常感谢Giorgos。这太完美了:@Sai很高兴我能帮上忙。请将此答案或任何其他答案标记为已接受,如果它有助于您解决问题。非常感谢Giorgos。这太完美了:@Sai很高兴我能帮上忙。请将此答案或任何其他答案标记为已接受,如果它有助于您解决问题。