我的一张桌子有这样的值..
Year 1
Year 9
Year 4
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 8
Year 22
Year 15....
我如何首先按字母顺序选择Them,然后按照数字顺序选择这样的..
Kindy [can be any word without numbers]
Pre-School [can be any word without numbers]
Year 1
Year 4
Year 8
Year 9
Year 15
Year 22
在这种情况下,我无法提取整数和顺序,因为有些年份没有它...
更新
我的答案 - 不和的意思
SELECT YearLevel FROM Student
ORDER BY
CASE WHEN YearLevel NOT LIKE '%[0-9]%' THEN 0
ELSE CAST(RIGHT(YearLevel, LEN(YearLevel) - 5) AS int)
END
答案 0 :(得分:0)
在ORDER BY
子句中尝试此操作:
ORDER BY
CASE WHEN col = 'Kindy' then 0
WHEN col = 'Pre-School' then 1
ELSE CAST(SUBSTRING(col,6,LEN(col)) AS INT) + 1
END
答案 1 :(得分:0)
首先,您必须为获取字符串的文本部分和数字部分创建以下函数:
CREATE FUNCTION [dbo].[GetNumbersFromText](@String varchar(2000))
RETURNS INT
AS BEGIN
DECLARE @Count INT = 0,
@IntNumbers VARCHAR(1000) = '',
@FindNumber BIT = 0
WHILE @Count <= LEN(@String) BEGIN
IF SUBSTRING(@String,@Count,1) >= '0' AND SUBSTRING(@String,@Count,1) <= '9' BEGIN
SET @IntNumbers = @IntNumbers + SUBSTRING(@String,@Count,1)
SET @FindNumber = 1
END ELSE IF (@FindNumber = 1) BEGIN
BREAK
END
SET @Count = @Count + 1
END
RETURN CAST(@IntNumbers AS INT)
END
CREATE FUNCTION [dbo].[GetTextPartOfText](@String varchar(2000))
RETURNS INT
AS BEGIN
DECLARE @Count INT = 0,
@Text VARCHAR(1000) = '',
WHILE @Count <= LEN(@String) BEGIN
IF SUBSTRING(@String,@Count,1) >= '0' AND SUBSTRING(@String,@Count,1) <= '9' BEGIN
BREAK
END ELSE BEGIN
SET @Text = @Text + SUBSTRING(@String,@Count,1)
END
SET @Count = @Count + 1
END
RETURN @Text
END
在第二步中,您使用以下查询进行排序:
SELECT *
FROM YourTable
ORDER BY [dbo].[GetTextPartOfText](TextColumn),[dbo].[GetNumbersFromText](TextColumn), TextColumn
答案 2 :(得分:0)
SELECT YearLevel FROM student
GROUP BY YearLevel
ORDER BY
(CASE
WHEN YearLevel LIKE 'Year%'
THEN 'Year' + CONVERT(varchar,LEN(YearLevel)) + YearLevel
ELSE YearLevel
END)