Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL中找到作为子字符串的int值的最小值和最大值?_Sql_Sql Server_Substring_Max_Min - Fatal编程技术网

如何在SQL中找到作为子字符串的int值的最小值和最大值?

如何在SQL中找到作为子字符串的int值的最小值和最大值?,sql,sql-server,substring,max,min,Sql,Sql Server,Substring,Max,Min,例如,我有下表: 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 |

例如,我有下表:

  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'
仅保留int。比较或获取最大值

SELECT CONCAT(MAX(CAST(REPLACE(cd,'x','') as int)) , 'x') cd_max
FROM T


如果可以假定字符串总是以
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
模式:

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');
sql:我假设只有最后一个字符不是数字

  select * from Detail order by cast(left(cd,len(cd)-1) as int)
输出:

pc  cd
pc0 4x
pc3 4x
pc2 8x
pc4 24x
pc1 24x
cd_max
24x
sql2:获取最大cd

select top(1) cd as cd_max from Detail order by cast(left(cd,len(cd)-1) as int) desc
输出:

pc  cd
pc0 4x
pc3 4x
pc2 8x
pc4 24x
pc1 24x
cd_max
24x