我有一个查询,其中第一列显示名称长度,第二列显示名称或礼貌我已经完成了这些但我的第三列遇到了问题。它应该使用子字符串并显示名字的首字母和姓氏初始,任何人都可以告诉我如何将此功能添加到我已经拥有的内容中吗?
这是查询
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name],
CASE TitleOfCourtesy WHEN 'Mr.' THEN 'Mister '
WHEN 'mrs. ' THEN 'Miss'
WHEN 'Ms.' THEN 'Miss '
WHEN 'Dr.' THEN 'Doctor '
ELSE '' END + TitleOfCourtesy + LastName AS title
FROM dbo.Employees
答案 0 :(得分:0)
(因为您使用了LEN我假设您使用的是SQL Server)
你的意思是这样的吗?
substring(FirstName,1,1) + substring(LastName,1,1)
一般情况是这样的:
substring(expression, startPosition, lenght)
答案 1 :(得分:0)
我会使用LEFT()而不是substring。
DECLARE @Employees TABLE (FirstName VARCHAR(25),LastName VARCHAR(25), TitleOfCourtesy VARCHAR(5))
INSERT INTO @Employees
VALUES ('Bob','Brown','Mr.'),
('Olivia','Taylor','M rs.'),
('Grace','Stevens','Ms.'),
('Theodor','Seuss','Dr.');
SELECT 'Your full name is ' + CAST(LEN(FirstName) + LEN(LastName) AS VARCHAR(12)) + ' character(s).' AS [Length of Employee Name],
CASE Replace(TitleOfCourtesy, ' ','') --Gets rid of any white space
WHEN 'Mr.' THEN 'Mister'
WHEN 'mrs.' THEN 'Miss'
WHEN 'Ms.' THEN 'Miss'
WHEN 'Dr.' THEN 'Doctor'
ELSE ''
END + ' ' + LastName AS title,
CONCAT(LEFT(FirstName,1),'.',LEFT(LastName,1),'.') AS Initials
FROM @Employees
结果:
Length of Employee Name title Initials
-------------------------------------------- -------------------------------- --------
Your full name is 8 character(s). Mister Brown B.B.
Your full name is 12 character(s). Miss Taylor O.T.
Your full name is 12 character(s). Miss Stevens G.S.
Your full name is 12 character(s). Doctor Seuss T.S.