我有一个包含
的数据的表格Item No. (1a)
Item No. (2)
Item No. (3)
Item No. (4)
Item No. (5)
Item No. (6)
Item No. (7)
Item No. (8)
Item No. (9)
Item No. (10)
现在假设这些并不总是按照这个完美的顺序,我希望这样当我选择它们时,它们会按顺序拉出来。但是,当我选择并尝试按任何顺序排序时,它会给我这个
Item No. (1a)
Item No. (10)
Item No. (2)
Item No. (3)
Item No. (4)
Item No. (5)
Item No. (6)
Item No. (7)
Item No. (8)
Item No. (9)
任何人都可以通过语句帮助我按顺序设置第一个订单吗?
答案 0 :(得分:1)
您可以使用模式拆分器来拆分字符串的数字组件。这是来自Dwain Camps' article
-- PatternSplitCM will split a string based on a pattern of the form
-- supported by LIKE and PATINDEX
--
-- Created by: Chris Morris 12-Oct-2012
CREATE FUNCTION [dbo].[PatternSplitCM]
(
@List VARCHAR(8000) = NULL
,@Pattern VARCHAR(50)
) RETURNS TABLE WITH SCHEMABINDING
AS
RETURN
WITH numbers AS (
SELECT TOP(ISNULL(DATALENGTH(@List), 0))
n = ROW_NUMBER() OVER(ORDER BY (SELECT NULL))
FROM
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) e (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) f (n),
(VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) g (n))
SELECT
ItemNumber = ROW_NUMBER() OVER(ORDER BY MIN(n)),
Item = SUBSTRING(@List,MIN(n),1+MAX(n)-MIN(n)),
[Matched]
FROM (
SELECT n, y.[Matched], Grouper = n - ROW_NUMBER() OVER(ORDER BY y.[Matched],n)
FROM numbers
CROSS APPLY (
SELECT [Matched] = CASE WHEN SUBSTRING(@List,n,1) LIKE @Pattern THEN 1 ELSE 0 END
) y
) d
GROUP BY [Matched], Grouper
现在您已经拥有了拆分器,您可以使用它来对数据进行排序:
SELECT t.val
FROM tbl t
CROSS APPLY (
SELECT TOP 1 CAST(Item AS INT)
FROM dbo.PatternSplitCM(t.val, '%[0-9]%')
WHERE Matched = 1
ORDER BY ItemNumber
)s(n)
ORDER BY s.n
答案 1 :(得分:0)
with cte as(
select '1a' as num
union select '2'
union select '3'
union select '4'
union select '5'
union select '6'
union select '7'
union select '8'
union select '9'
union select '10') select num from cte order by case when ISNUMERIC(num) = 0 then 0 else convert(int,num) end asc
诀窍是按isnumeric(num)= 0的情况顺序,然后0,否则转换(int,num)结束asc。