SQL Order By和varchar

时间:2016-07-11 10:00:41

标签: sql sql-server sql-order-by

我想订购一个包含整数和字符串的nvarchar类型的列。我想首先订购整数ASC然后是字符串。 这是我的SQL语句:

SELECT DISTINCT [Password] 
FROM OCPR 
WHERE [Password] IS NOT NULL
ORDER BY Password

结果为1, 10, 11, 12, 2, 3, K1, K2, N

我想要1, 2, 3, 10, 11, 12, K1, K2, N

5 个答案:

答案 0 :(得分:2)

ISNUMERIC没有回答您认为的问题。例如, ISNUMERIC('£') will return 1 ,但尝试将其转换为int时会出错。 - Damien_The_Unbeliever

在您的数据库中创建此功能,该功能更好比内置的ISNUMERIC()更强,始终完全正确!

CREATE FUNCTION dbo.IsAllDigits (@MyString VARCHAR(8000))
RETURNS TABLE AS
RETURN (
         SELECT CASE 
                WHEN @MyString NOT LIKE '%[^0-9]%'
                THEN 1
                ELSE 0
                END AS IsAllDigits
        )

然后使用此代码:

SELECT DISTINCT [Password] 
FROM OCPR 
WHERE [Password] IS NOT NULL
ORDER BY
    CASE WHEN IsAllDigits([Password]) = 1 THEN 0 ELSE 1 END,
    CASE WHEN IsAllDigits([Password]) = 1 THEN CAST([Password] AS INT) ELSE 0 END,
    [Password]

答案 1 :(得分:1)

SELECT DISTINCT [Password] 
FROM OCPR 
WHERE [Password] IS NOT NULL
ORDER BY
    CASE WHEN ISNUMERIC(Password) = 1 THEN 0 ELSE 1 END,
    CASE WHEN ISNUMERIC(Password) = 1 THEN CAST(Password AS INT) ELSE 0 END,
    Password

请试试这个。

答案 2 :(得分:1)

您可以将Patindex用于此

Declare @Tasks table(id [nvarchar](max) NOT NULL)

insert into @tasks values ('1'),('7'),('2'), ('12'),('23'),('10'),('K1'), ('K2'), ('P'), ('N')

SELECT * FROM @tasks
ORDER BY 
CASE 
  WHEN ISNUMERIC(id)=1 
  THEN CAST(id as int)

  WHEN PATINDEX('%[^0-9]%',id) > 1 
  THEN CAST(
    LEFT(
      id,
      PATINDEX('%[^0-9]%',id) - 1
    ) as int)

  ELSE 2147483648
END, 


CASE 
  WHEN ISNUMERIC(id)=1 
  THEN NULL

  WHEN PATINDEX('%[^0-9]%',id) > 1 
  THEN SUBSTRING(
      id,
      PATINDEX('%[^0-9]%',id) ,
      50
    ) 

  ELSE id
END

答案 3 :(得分:1)

SELECT DISTINCT [Password] 
FROM OCPR 
WHERE [Password] IS NOT NULL
ORDER BY Password ASC

/////////////////////////////////////////////// //////////

SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;

$ query_test =“SELECT DISTINCT OCPR。密码                 来自OCPR                 WHERE OCPR。密码不是NULL                 ORDER BY OCPR。密码“;

答案 4 :(得分:1)

你可以使用ISNUMERIC函数来完成它。 您的查询将如下所示:

SELECT DISTINCT [Password] 
FROM OCPR 
WHERE [Password] IS NOT NULL
ORDER BY 
CASE WHEN ISNUMERIC([Password])=1 THEN CONVERT(int,[Password]) ELSE 99999999 END,
[Password]

希望这有帮助;)