请使用以下查询帮助我,请修改并让我知道,我使用ssms
我只需要显示Phonenumber
。以下是我目前使用的查询。我将其分为两列,因为可能会有cell number
和home phone
。
CONCAT(RIGHT(LEFT(HR_PN_1.PhoneNumberID, 4), 3), REPLACE(RIGHT(HR_PN_2.PhoneNumberID, 8), '-', '')) as 'PersonPhone',
CASE
WHEN HR_PN_2.PhoneNumberID is not null
THEN CONCAT(RIGHT(LEFT(HR_PN_2.PhoneNumberID, 4), 3), REPLACE(RIGHT(HR_PN_2.PhoneNumberID, 8), '-', ''))
END as 'PersonWorkPhone',
我在表PhoneNumnberID
中的HR_PN_1 and HR_PN_2
列中的数据示例如下:
(123)456-7890TOMMY
(123)456-7890 DAD
(123)456-7890 ***
(123)456-7890 2300
(123)456-7890CELL#
(123)456-7890
我需要将这些号码仅显示为电话号码格式(123)456-7890
答案 0 :(得分:3)
如果这些是列中的值,那么您似乎想要:
LEFT(HR_PN_1.PhoneNumberID, 13)
答案 1 :(得分:0)
如果这些电话号码始终位于开头,则只需一个LEFT就足够了。
如果电话号码的位置可以更改,但始终采用相同的格式?
然后,您可以将SUBSTRING与PATINDEX结合使用。
declare @HR_PN_1 table (HR_ID int identity (1,1) primary key, PhoneNumberID varchar(100));
declare @HR_PN_2 table (HR_ID int identity (1,1) primary key, PhoneNumberID varchar(100));
insert into @HR_PN_1 (PhoneNumberID) values
('(123)456-7891TOMMY'),
('(123)456-7892 DAD'),
('(123)456-7893 ***'),
('(123)456-7894 2300'),
('(123)456-7895CELL#'),
('(123)456-7896'),
('no phone');
insert into @HR_PN_2 (PhoneNumberID)
select PhoneNumberID
from @HR_PN_1
order by HR_ID desc;
SELECT hr1.HR_ID,
(CASE
WHEN hr1.PhoneNumberID like '%([0-9][0-9][0-9])[0-9][0-9][0-9]_[0-9][0-9][0-9][0-9]%'
THEN SUBSTRING(hr1.PhoneNumberID, PATINDEX('%([0-9][0-9][0-9])[0-9][0-9][0-9]_[0-9][0-9][0-9][0-9]%', hr1.PhoneNumberID), 13)
END) AS "PersonPhone",
(CASE
WHEN hr2.PhoneNumberID like '%([0-9][0-9][0-9])[0-9][0-9][0-9]_[0-9][0-9][0-9][0-9]%'
THEN SUBSTRING(hr2.PhoneNumberID, PATINDEX('%([0-9][0-9][0-9])[0-9][0-9][0-9]_[0-9][0-9][0-9][0-9]%', hr2.PhoneNumberID), 13)
END) AS "PersonWorkPhone"
FROM @HR_PN_1 AS hr1
LEFT JOIN @HR_PN_2 AS hr2 ON (hr2.HR_ID = hr1.HR_ID);
然后将其包装在CASE中只是为了避免返回非电话号码的内容。
示例片段:
ax = gca()
答案 2 :(得分:0)
怎么样?
SELECT SUBSTRING(yourcolumn, PATINDEX('%([0-9][0-9][0-9])[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]%',yourcolumn), 13)
FROM yourtable