我在 JobDetails 表中有一个工作名称列。像这样
job Name
A_1
A_2
B_1
B_2
B_3
我像这样搜索最大数量
SELECT MAX(JobDetails.[Job Name])
FROM Monara.JobDetails
WHERE
( [Job Name] like 'B_%' )
结果是 B_3
但我只想得到3个。
我该怎么做?
我在 JobDetails 表中有一个工作名称列。像这样
job Name
A_1
A_2
B_1
B_2
B_3
我像这样搜索最大数量
SELECT MAX(JobDetails.[Job Name])
FROM Monara.JobDetails
WHERE
( [Job Name] like 'B_%' )
结果是 B_3
但我只想得到3个。
我该怎么做?
我拒绝创建包含空格的列
下划线是一个通配符,使用Like时应小心处理
create table JobDetails ([JobName] varchar(10))
insert JobDetails values('A_1'),('A_2'),('B_1'),('B_2'),('B_3')
SELECT max(cast(stuff(JobName, 1, patindex('%[_]%', JobName), '') as int))
FROM JobDetails
WHERE JobName like 'B[_]%'
-- added check to prevent most bad data
and IsNumeric(stuff(JobName, 1, patindex('%[_]%', JobName), '')) > 0
试试这个代码:
SELECT SUBSTRING(JobDetails.[Job Name],
( SELECT CHARINDEX('_', JobDetails.[Job Name])
) + 1,
LEN(JobDetails.[Job Name]) -
CHARINDEX('_', JobDetails.[Job Name])
+ 1)
FROM Monara.JobDetails
WHERE [Job Name] LIKE 'B_%'
SELECT count(JobDetails.[Job Name])
FROM Monara.JobDetails
WHERE [Job Name] like 'B_%'