在执行订单时将数值置于底部?

时间:2015-09-01 06:29:36

标签: sql sql-server

这是事情,我对sql查询不好。当我想在mssql中执行命令时,我想将数值放在底部。

我的查询是:

SELECT DISTINCT code,value 
FROM code_value 
WHERE code = 'BR' 
ORDER BY value

我得到的结果就是这个

code value
BR   122333
BR   1455577
BR   193 Your Kart
BR   Junglee
BR   Kart Info
BR   Snapdeal
BR   Your Kart

我希望输出如下

code value
BR   Junglee
BR   Kart Info
BR   Snapdeal
BR   Your Kart
BR   122333
BR   1455577
BR   193 Your Kart

有没有可用的解决方法来实现这一目标?

2 个答案:

答案 0 :(得分:3)

ORDER BY 
case when string_value like '[0-9]%' then 1 else 0 end,string_value

修改

select  code,value from
(
SELECT DISTINCT top 100 percent code,
case when value like '[0-9]%' then 1 else 0 end as rank,value 
FROM code_value 
WHERE code = 'BR' 
ORDER BY 
case when value like '[0-9]%' then 1 else 0 end,value
) as t

答案 1 :(得分:1)

另一种适用于您的特定示例的方法,使用自定义函数

CREATE Function [dbo].[RemoveNonNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @KeepValues as varchar(50)
    Set @KeepValues = '%[^0-9]%'
    While PatIndex(@KeepValues, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@KeepValues, @Temp), 1, '')

    Return @Temp
End

然后,在你的背景下:

SELECT DISTINCT code,value 
FROM code_value 
WHERE code = 'BR' 
order by dbo.RemoveNonNumericCharacters(value), value

请注意,除了特定示例的范围之外,此解决方案可能无法按预期工作。示例:如果VALUE在字符串中的某处包含数字,但不以数字值开头。要处理这种情况,必须修改该函数。