例如,
我有这样的输出: -
ID
---
AB1
AB2
AB3
AB4
BD6
如果我使用MAX(ID)
,我会得到'BD6'
但我想查看MAX
价值模式AB
我怎么能得到它?
答案 0 :(得分:2)
只需过滤带有ID的数据字段,然后使用Max():
编辑:如果ID包含的数字超过1位数:
SELECT TOP 1 *
FROM
[Table] AS A
WHERE
RIGHT(ID, LEN(ID) - 2) = (SELECT
MAX(Cast(RIGHT(ID, LEN(ID) - 2) AS Int)) FROM [Table] WHERE ID LIKE 'AB%')
AND
ID LIKE 'AB%'
答案 1 :(得分:1)
试试这个。它将显示每个String的所有最大ID。
select CONCAT(ID,id1) as ID from
(
select left(id, patindex('%[^0-9]%', id) + 1) ID , max(cast(substring(id, PatIndex('%[0-9]%', id),len(id)) as numeric)) id1
from #Table
group by left(id, patindex('%[^0-9]%', id) + 1)
)a
对于特定ID值,例如' AB'将值放入where子句。
select CONCAT(ID,id1) as ID from
(
select left(id, patindex('%[^0-9]%', id) + 1) ID , max(cast(substring(id, PatIndex('%[0-9]%', id),len(id)) as numeric)) id1
from #Table
group by left(id, patindex('%[^0-9]%', id) + 1)
)a
where ID like '%ab%'
OutPut:
outpur for AB111
此处还可以查看demo。
答案 2 :(得分:0)
试试这个:
SELECT 'AB' + CONVERT(NVARCHAR(10),MAX(CONVERT(INT, Nums.Numbers)))
FROM (SELECT Substring(ID, 3, 10) as Numbers
FROM #Tab tab
WHERE tab.ID LIKE 'AB%') as Nums
你可以在这里看到这个=> http://rextester.com/MAHKWE99983
希望这有帮助!!!
答案 3 :(得分:0)
试试吧,
DECLARE @TABLE TABLE(ID VARCHAR(MAX))
INSERT INTO @TABLE (ID)
VALUES('AB1'),('AB2'),('AB3'),('AB4'),('AB11'),('AB111'),('XY112')
DECLARE @Prefix VARCHAR (10) = 'AB'
SELECT @Prefix + CAST(MAX(CAST(SUBSTRING(ID, (LEN(@Prefix) + 1),
(LEN(ID) - 2)) AS INT)) AS VARCHAR) AS ID FROM @TABLE WHERE ID LIKE
@Prefix +'%'
答案 4 :(得分:0)
您可以通过此查询获取。
create table temp
(
id varchar(10)
);
insert into temp values
('AB111'),
('AB1'),
('AB2'),
('AB3'),
('AB4'),
('BD6'),
('AB111')
;
declare @Pattern varchar(5)
set @Pattern='AB'
select distinct(Id) from temp where Id = @Pattern+convert(varchar(10),(
select MAX(Id) as Maximum from (
SELECT convert(integer,REPLACE( Id,@Pattern,'')) as Id FROM temp
where id like 'AB%'
)as test ))
答案 5 :(得分:-1)
with tmp as (
select 'AB1' id union all
select 'AB2' id union all
select 'AB3' id union all
select 'AB4' id union all
select 'AB111' id union all
select 'BD6' id
)
select top 1 * from tmp f1
where f1.ID LIKE 'AB%' and cast(SUBSTRING(f1.ID, 3, LEN(ID) -2) as integer) in
(
select max(cast(SUBSTRING(f2.ID, 3, LEN(ID) -2) as integer)) from tmp f2
WHERE f2.ID LIKE 'AB%'
)
答案 6 :(得分:-2)
SELECT MAX(ID) FROM #Tbl
GROUP BY LEFT(col_name,2)