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

时间:2016-06-17 18:49:59

标签: sql sql-server

你能帮我解决一下在下表Balance列中计算负值和正值数的SQL查询。非常感谢任何帮助。

Attached the table image for your refeerence

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合

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)

并为正值做同样的事情。

答案 1 :(得分:0)

您需要在小组中使用CASE

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