如何在内部使用计数

时间:2016-04-26 03:14:58

标签: sql sql-server

请帮我计算一下案例陈述。

我想要这个结果:

Equal : 50
GT : 25
LT : 15

以下是我的代码:

select Input,
      CASE
      when math = '=' then 
        count(case when Input = UDTarget then Input else 0 end)
      end as Equals,
      CASE
      when math = '>' then 
        count(case when ISNUMERIC(Input) < ISNUMERIC(UDTarget) then Input else 0 end)
      end as GT,
      CASE when math = '<' then 
        count(case when ISNUMERIC(Input) > ISNUMERIC(UDTarget) then Input else 0 end)  
      END as LT 
FROM [NEWSEMAKPI].[dbo].[NewCriteria] NC 
inner join [NEWSEMAKPI].[dbo].[UpdateData] UD ON UD.Cid = NC.Id 
where InputWeek='15' 
group by Input 

1 个答案:

答案 0 :(得分:1)

您的错误已显示,因为您未在math条款中添加group by。所以你应该把它放进去:

select Input,
      CASE
      when math = '=' then 
        count(case when Input = UDTarget then Input else 0 end)
      end as Equals,
      CASE
      when math = '>' then 
        count(case when ISNUMERIC(Input) < ISNUMERIC(UDTarget) then Input else 0 end)
      end as GT,
      CASE when math = '<' then 
        count(case when ISNUMERIC(Input) > ISNUMERIC(UDTarget) then Input else 0 end)  
      END as LT 
FROM [NEWSEMAKPI].[dbo].[NewCriteria] NC 
inner join [NEWSEMAKPI].[dbo].[UpdateData] UD ON UD.Cid = NC.Id 
where InputWeek='15' 
group by Input, math