【问题标题】:How to find MIN and MAX of int values as substrings in SQL?如何在 SQL 中查找 int 值的 MIN 和 MAX 作为子字符串?
【发布时间】:2019-02-21 15:48:37
【问题描述】:

例如,我有下表:

  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。

【问题讨论】:

    标签: sql sql-server substring max min


    【解决方案1】:

    你可以尝试replece 'x'只保留int。比较或获取最大值。

    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) 
    

    【讨论】:

      【解决方案2】:

      如果假设字符串总是以x 结尾是可以的,我会将其切断,将字符串转换为数字,找到最大值并重新打开x

      SELECT MAX(CAST(LEFT(cd, LEN(cd) - 1) AS INT)) + 'x'
      FROM   mytable
      

      【讨论】:

        【解决方案3】:

        将结尾的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
        

        【讨论】:

          【解决方案4】:

          架构:

          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
          

          sql2: 获取最大 cd

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

          输出:

          cd_max
          24x
          

          【讨论】:

            猜你喜欢
            • 2022-11-14
            • 1970-01-01
            • 1970-01-01
            • 2014-03-15
            • 2020-11-22
            • 1970-01-01
            • 1970-01-01
            • 2021-05-04
            • 2018-05-26
            相关资源
            最近更新 更多