例如,我有下表:
pc | cd
---------------
pc0 | 4x
pc1 | 24x
pc2 | 8x
pc3 | 4x
pc4 | 24x
我需要得到这样的东西:
cd_max
--------
24x
或者排序:
pc | cd
---------------
pc0 | 4x
pc3 | 4x
pc2 | 8x
pc1 | 24x
pc4 | 24x
“24x”显然是字符串,但我需要在其中获得最大/最小整数。
我正在使用MS SQL Server。
如果可以假设字符串将始终以x
结尾,我会将其剪掉,将字符串转换为数字,找到最大值并重新打开x
:
SELECT MAX(CAST(LEFT(cd, LEN(cd) - 1) AS INT)) + 'x'
FROM mytable
切片的尾随x
并将varchar
投射到int
如下:
cast(left(cd, len(cd) - 1) as int)
现在您可以按此值排序并选择最大值:
select top 1 cd as cd_max
from my_table
order by cast(left(cd, len(cd) - 1) as int) desc
您可以尝试替换qazxsw poi只保留in。比较或获得最大值。
'x'
要么
SELECT CONCAT(MAX(CAST(REPLACE(cd,'x','') as int)) , 'x') cd_max
FROM T
模式:
SELECT *
FROM T
ORDER BY CAST(REPLACE(cd,'x','') AS INT)
sql:我假设只有最后一个字符不是数字
create table Detail (pc varchar(100) ,cd varchar(100) );
insert into Detail values ('pc0','4x');
insert into Detail values ('pc1','24x');
insert into Detail values ('pc2','8x');
insert into Detail values ('pc3','4x');
insert into Detail values ('pc4','24x');
输出:
select * from Detail order by cast(left(cd,len(cd)-1) as int)
sql2:获取最大cd
pc cd
pc0 4x
pc3 4x
pc2 8x
pc4 24x
pc1 24x
输出:
select top(1) cd as cd_max from Detail order by cast(left(cd,len(cd)-1) as int) desc