从存储过程的混合字符串/整数列中选择最大值?

时间:2019-03-27 07:43:34

标签: sql sql-server tsql stored-procedures

我有一列为varchar。我将值存储在其中,如下所示:-

P.ID
P1
P2
.
.
P6
.
P11 

我只想从此列中选择最高的id,例如:p11是我的最高ID。

我现有的查询是:

SELECT top(1) P.ID as Result from P order by P.ID desc

4 个答案:

答案 0 :(得分:1)

我认为一个简单的方法是:

select top (1) pid
from p
order by len(pid) desc, pid desc;

答案 1 :(得分:0)

根据您提供的内容,您可以做

SELECT MAX(CAST(RIGHT(YourColumn, LEN(YourColumn)-1) AS BIGINT))
FROM TBL;

例如:

WITH CTE AS
(
  SELECT 'P1' AS Col
  UNION
  SELECT 'P2'
  UNION
  SELECT 'P100'
)
SELECT MAX(CAST(RIGHT(Col, LEN(Col)-1) AS BIGINT))
FROM CTE;

哪个会返回:100

答案 2 :(得分:0)

尝试此查询:

select top 1 *
from P
order by cast(substring(P.ID, 2, len(P.ID)) as int) desc

它只是按列中包含的整数排序。

答案 3 :(得分:0)

尝试一下

;WITH CTE ([P.ID])
AS
(
SELECT 'P1' UNION ALL
SELECT 'P2' UNION ALL
SELECT 'P6' UNION ALL
SELECT 'P11' 
)
SELECT TOP 1 *
FROM CTE
ORDER BY  CAST(SUBSTRING([P.ID],PATINDEX('%[0-9]%',[P.ID]),LEN([P.ID])) AS INT) DESC

结果

P.ID
----
P11