如何获取已与sqlserver中的字符混合的Max值

时间:2017-04-10 07:27:05

标签: sql-server

我有一个像这样定义的表:

Name       Value
-----      -----
Alice      MN21
Bob        MN22

我希望得到像

这样的最大值
select Name,MAX(Value) as Value from #Character

它会显示

Name      Value
----      -----
Bob       MN22

有什么想法吗?

5 个答案:

答案 0 :(得分:1)

您可以使用 SUBSTRING 获取与以下相同格式的数字:

SELECT TOP(1)
    Name, 
    Value,
    SUBSTRING(Value,3,LEN(Value)) AS MaxValue
FROM @tblTest order by CAST(SUBSTRING(Value,3,LEN(Value)) AS INT) DESC

答案 1 :(得分:1)

你需要这样的东西吗?

CREATE TABLE #CH (NAME VARCHAR(20), VALUE VARCHAR(10))
INSERT INTO #CH VALUES ('Alice', 'MN21'), ('Bob', 'MN22'), ('Angie', 'AO42'),('Karl', 'AO27');
SELECT NAME, MAXVAL, VALUE
FROM #CH
INNER JOIN (SELECT SUBSTRING(VALUE,1,2) AS LEFTPART, MAX(SUBSTRING(VALUE,3,2)) AS MAXVAL
            FROM #CH 
            GROUP BY SUBSTRING(VALUE,1,2)) B ON #CH.VALUE = B.LEFTPART+B.MAXVAL

Output:
NAME                 MAXVAL VALUE
-------------------- ------ ----------
Bob                  22     MN22
Angie                42     AO42

答案 2 :(得分:1)

简单是最好的

select top 1 Name,Value from #Character order by Value desc

答案 3 :(得分:0)

试试这个

select Name,Value from #Character where value in (
   select MAX(CAST(value AS int)) from #Character)

答案 4 :(得分:0)

试试这个

select Name,MAX(Value REGEXP '[0-9]{5}') as Value from #Character