SQL where where case语句

时间:2016-01-21 17:29:04

标签: sql-server if-statement case where exists

我不确定如何将if/casewhere exists语句合并。以下所有字段均位于t_phone

这是设置 - 有一个声明的电话临时变量

Declare @phone varchar(25)

`select @phone = ....`

我们需要说的是,对于给定的customer_no,如果{customer = no}存在phone_type(来自t_phone),则类型为25,使用与type = 25关联的phone_no,否则使用类型2.

所以例如

phone_no          type           customer_no
1234567890          2                  4
0987654321          25                 4
6537327345          2                  8

基于客户4的上述示例,我们要设置@phone = 0987654321,因为存在类型25,但对于客户编号8,我们要使用类型2,因为没有替代25类型。

4 个答案:

答案 0 :(得分:1)

如果2和25是唯一类型,您可以执行以下SELECT MAX()

Select t.phone_no
from t_phone t
where t.type = (select max(ti.type) 
                from t_phone ti 
                where ti.customer_no=t.customer_no 
                and ti.type in (2,25))

答案 1 :(得分:1)

通过引入名为type_priority的表,您可以更轻松地实现维护。这将有两列:typepriority。对于type=25priority最高为10,而type=2 priority则为1。

然后,当您选择此表格的加入时,请按priority DESC排序并选择top 1

select top 1 @phone = phone_no
from t_phone ph
join type_priority tp on tp.type = ph.type
where customer_no = @Customer
order by tp.priority desc

这种数据驱动方法更易于维护'如果你引入其他类型,只需用type_prioritypriority表添加行,并且sql语句继续工作。

请注意,对于types表中缺少type_priority,将不会选择记录。因此,您需要确保它与所有新引入的类型保持同步。

答案 2 :(得分:0)

由于您只与单个客户打交道,并且您想要的唯一值是2型和25型,如此简单。

select top 1 phone_no
from t_phone
where customer_no = @Customer
order by 
case type when 25 then 2
    when 2 then 1
    else 0 end

答案 3 :(得分:0)

declare @phone varchar(25)
select @phone = CASE t0.[type]
                WHEN 25 THEN t1.phone_no 
                WHEN 2 then t2.phone_no             
                else 0
                END
from tbl t0
left outer join tbl t1 on t1.type = 25 and t1.customer_no = t0.customer_no
left outer join tbl t2 on t2.type = 2 and t2.customer_no = t0.customer_no