好吧我在here上问了同样的jquery问题,现在我的问题与SQL Server Query相同:)但这次不是逗号分隔,这是数据库中的单独行
我已经分隔了具有浮点数的行。
Name
K1.1
K1.10
K1.2
K3.1
K3.14
K3.5
我希望对这个浮动数字进行排序,例如,
Name
K1.1
K1.2
K1.10
K3.1
K3.5
K3.14
实际上在我的情况下,小数点后的数字将被视为自然数,因此1.2将被视为“2”,1.10将被视为“10”,这就是为什么1.2将首先出现在1.10之后。
你可以删除'K',因为它几乎是常见的,建议或示例对我来说都很棒,谢谢。
答案 0 :(得分:2)
如果在第一个数字之前总是有一个字符且数字不高于9,则此方法有效:
SELECT name
FROM YourTable
ORDER BY CAST(SUBSTRING(name,2,1) AS INT), --Get the number before dot
CAST(RIGHT(name,LEN(name)-CHARINDEX('.',name)) AS INT) --Get the number after the dot
答案 1 :(得分:2)
也许,更多的口头,但应该做的伎俩
declare @source as table(num varchar(12));
insert into @source(num) values('K1.1'),('K1.10'),('K1.2'),('K3.1'),('K3.14'),('K3.5');
-- create helper table
with data as
(
select num,
cast(SUBSTRING(replace(num, 'K', ''), 1, CHARINDEX('.', num) - 2) as int) as [first],
cast(SUBSTRING(replace(num, 'K', ''), CHARINDEX('.', num), LEN(num)) as int) as [second]
from @source
)
-- Select and order accordingly
select num
from data
order by [first], [second]
sqlfiddle: http://sqlfiddle.com/#!6/a9b06/2
答案 2 :(得分:2)
您可以使用PARSENAME
(更多是黑客)或字符串函数(如CHARINDEX
,STUFF
,LEFT
等来实现此目的。
输入数据
;WITH CTE AS
(
SELECT 'K1.1' Name
UNION ALL SELECT 'K1.10'
UNION ALL SELECT 'K1.2'
UNION ALL SELECT 'K3.1'
UNION ALL SELECT 'K3.14'
UNION ALL SELECT 'K3.5'
)
使用PARSENAME
SELECT Name,PARSENAME(REPLACE(Name,'K',''),2),PARSENAME(REPLACE(Name,'K',''),1)
FROM CTE
ORDER BY CONVERT(INT,PARSENAME(REPLACE(Name,'K',''),2)),
CONVERT(INT,PARSENAME(REPLACE(Name,'K',''),1))
使用字符串函数
SELECT Name,LEFT(Name,CHARINDEX('.',Name) - 1), STUFF(Name,1,CHARINDEX('.',Name),'')
FROM CTE
ORDER BY CONVERT(INT,REPLACE((LEFT(Name,CHARINDEX('.',Name) - 1)),'K','')),
CONVERT(INT,STUFF(Name,1,CHARINDEX('.',Name),''))
<强>输出强>
K1.1 K1 1
K1.2 K1 2
K1.10 K1 10
K3.1 K3 1
K3.5 K3 5
K3.14 K3 14
答案 3 :(得分:-1)
较短的解决方案就是这个:
Select Num
from yourtable
order by cast((Parsename(Num, 1) ) as Int)