SQL:如何创建if语句

时间:2015-08-03 10:32:44

标签: sql-server conditional

我对MS SQL很新,所以请耐心等待。

我有一个关于客户信息的表格,我想在其中添加列和输入值"是"或"不"取决于表中某些值的结果。

基本上,我需要这样的东西

SELECT customer_no, reg_no, @result_101, @result_301
      IF(reg_no*100)+other_number = 101
      THEN @result_101 = 'yes'
      ELSE @result_101 = 'no'

      IF(reg_no*100)+other_number = 301
      THEN @result_301 = 'yes'
      ELSE @result_301 = 'no' 
FROM customer_table

客户是否有可能得到“是”'在两列中,因为它们有几个" other_number"?

我无法弄清楚如何使用CASE语句解决这个问题 - 因为它只会创建双行,因此每个客户都会在结果集上显示两次,例如

customer_no      reg_no      @result_101     @result_301
01               0101         yes             no
01               0101         no              yes
02               0101         yes             no
02               0101         no              yes

我需要将它们聚集成一行。

2 个答案:

答案 0 :(得分:1)

您正在寻找的是case表达式:

SELECT 
  customer_no, reg_no, 
  result_101 = CASE 
                WHEN (reg_no*100)+other_number = 101 THEN 'yes'
                ELSE 'no'
               END,
  result_301 = CASE 
                WHEN (reg_no*100)+other_number = 301 THEN 'yes'
                ELSE 'no' 
               END
FROM customer_table

我从列名中删除了@符号,因为@用于变量,但如果您真的需要它,可以将其括在括号中:[@result_101]

如果要避免重复行,可能需要对case表达式使用一些聚合函数。

答案 1 :(得分:1)

您可以使用IIF获得更简单,更清洁的解决方案:

像这样:

SELECT 

  customer_no, 
  reg_no, 
  IIF (reg_no * 100 + other_number = 101, 'yes', 'no') AS reg_101,
  IIF (reg_no * 100 + other_number = 301, 'yes', 'no') AS reg_301       

FROM customer_table

这仅适用于使用MS-SQL 2012或更高版本

的情况