多个参数的一个case语句

时间:2018-01-30 16:21:00

标签: sql sql-server select case

以下是我的示例代码情况

declare @Ka int = select count(empid) from employee where age between 18 and 22
declare @Kb int = select count(empid) from employee where age between 23 and 30
declare @Kc int = select count(empid) from employee where age between 31 and 35

现在,如果Ka / Kb / Kc的某个值不是0或null,那么它应该显示'x',否则它应该显示为空白。所以我的选择声明是:

select  
   CASE WHEN @Ka = 0 then ''  
        ELSE 'X' 
        END AS 'Ka',
   CASE WHEN @Kb = 0 then ''  
        ELSE 'X' 
        END AS 'Kb',
   CASE WHEN @Kc = 0 then ''  
        ELSE 'X' 
        END AS 'Kc'

所以如果我有更多的参数,我应该如上所述为每个参数做一个case语句吗?有没有办法做单个案例陈述,包括服从条件的所有参数?或者有一种简单的方法来完成类似的事情吗?

2 个答案:

答案 0 :(得分:2)

为什么这样?如果您要执行以下操作(没有变量),它似乎更有效:

Array ( [0] => [other, could, be, here] [1] => [and,more,here] )

答案 1 :(得分:1)

没有。不要这样做。您需要里面的查询:

select sum(case when age between 18 and 22 then 1 else 0 end) as age_18_22,
       sum(case when age between 23 and 30 then 1 else 0 end) as age_23_30,
       sum(case when age between 31 and 35 then 1 else 0 end) as age_31_35       
from employee e; 

SQL不通过替换查询字符串中的文本来工作。我的意思是,你可以这样做 - 它被称为动态sql 。但是你应该首先学习表达查询的基础知识。