如果电话号码与提供的电话号码相匹配,我需要一个SQL查询来返回电话号码,或者返回最近订购的电话号码列表的第一个值。
假设客户有3个电话号码:
ID ClientID Number Order
1 1 07123123123 2
2 1 07321321321 3
3 1 07111111111 1
如果查询中提供的电话号码是07321321321,那么它将返回07321321321.如果提供的电话号码没有匹配任何号码或是黑色,它将返回前1号码,由订单栏。
是否有明显的方法可以执行此操作,或者使以下SQL工作?
SELECT TOP 1 Number
FROM ClientPhoneNumbers cpn
WHERE cpn.ClientId = clientlist.ClientId
ORDER BY (Number = <phonenumbersupplied>), cpn.[Order]) AS [PhoneNumber]
使用SQL-Server
谢谢!
答案 0 :(得分:1)
您可以将value
构造函数与JOIN
:
select top 1 cpn.number
from ClientPhoneNumbers cpn left join (
values ('07321321321')
) tt (number)
on tt.number = cpn.number
order by (case when tt.number is not null then 0 else cpn.[order] end);
答案 1 :(得分:1)
我想我会这样做:
select top (1) number
from ((select @number, 1 as ord
from ClientPhoneNumbers
where number = @number
) union all
(select top (1) number, 2
from ClientPhoneNumbers
order by order
)
) cp
order by ord;
你也可以这样做:
select top (1) cpn.number
from ClientPhoneNumbers cpn
order by (case when cpn.number = @number then 1 else 2 end),
cpn.order;