简体   繁体   中英

How to use count inside case

Please help me to count using case statement.

I want this result:

Equal : 50
GT : 25
LT : 15

Below is my code:

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 

Your error is shown because you didn't put math in your group by clause. So you should put it inside:

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM