我需要从数据库中检索唯一的手机号码。
问题是数字没有固定格式,有些以
+CountryCode
或 00CountryCode
或没有 +
和国家代码
所以我想使用 If 来操纵它们以具有单一格式。 但我不想改变数据库中的值(value)我只想改变它 在查询本身。
我不知道如何使用 DISTINCT
这是我目前所做的
SELECT DISTINCT PhoneNumber
FROM User
where (len(PhoneNumber) = 13 or len(PhoneNumber) = 10 or phoneNumber like '311%' or phoneNumber like '00311%' )
最佳答案
使用case when
。这是MySQL
select distinct case when length(phone) = 10 then concat('00382', right(phone ,(length(phone)-1)))
when length(phone) = 13 then replace(phone, '+', '00')
when length(phone) = 12 then concat ('00', phone)
else phone
end
from myTable;
这里我假设您的电话号码长度为 10 位,例如:0123456789 我还假设当数字有国家代码时,第一位数字不会显示,例如:00382123456789(14 位长)。
假设我已经这样做了:
如果号码长 10 位 (0123456789),请添加国家代码 (00382) 和 删除第一个数字 (0)
如果数字是 13 位长,则将 + 替换为 00
如果号码长12位则加00
这是 DEMO
下面是SQLServer的解决方案:
select distinct case when len(phone) = 10 then concat('00382', right(phone ,(len(phone)-1)))
when len(phone) = 13 then replace(phone, '+', '00')
when len(phone) = 12 then concat ('00', phone)
else phone
end
from myTable;
关于sql - 操纵选择查询的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58951953/