Sql server SQL:如何生成if语句
我是SQL女士的新手,所以请容忍我 我有一个关于客户信息的表格,我想根据表格中某些值的结果添加列和“是”或“否”的输入值 基本上,我需要这样的东西Sql server SQL:如何生成if语句,sql-server,conditional,Sql Server,Conditional,我是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)+
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
客户是否可能在两列中都得到“是”,因为他们有几个“其他号码”
我真的不知道如何用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
我需要将它们收集到一行。您要查找的是
案例
表达式:
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\u 101]
如果要避免重复行,可能需要在case表达式中使用一些聚合函数 您可以使用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或更高版本时有效Use
CASE。。。什么时候结束
在示例中,当客户有两行时,您希望显示什么?