SQL - 排序英语和日语的字母数字值

时间:2016-06-24 09:03:57

标签: sql sql-server sql-server-2008-r2

我不确定它是否可行,但我的列中包含一些像这样的英语和日语值

**section**
AHU-1-1
AHU-1-10
AHU-1-1-1
AHU-1-1-2
AHU-1-2
AHU-1-3
AHU-1-8
AHU 1
AHU 11
AHU 2
賃貸人側 1連絡先
更新連絡先

现在我想要一个排序值为 -

的输出
**Section**
AHU 1
AHU 2
AHU 11
AHU-1-1
AHU-1-2
AHU-1-3
AHU-1-8
AHU-1-10
AHU-1-1-1
AHU-1-1-2
賃貸人側 1連絡先
更新連絡先

我尝试了以下查询,但它仅适用于英语语言的值。不适用于日语价值观。

SELECT Section
FROM dbo.Section
ORDER BY LEFT(replace(Section,'-','0'),PATINDEX('%[0-9]%',replace(Section,'-    ','0'))-1), -- alphabetical sort
     CONVERT(INT,SUBSTRING(replace(Section,'-','0'),PATINDEX('%[0-9]%',replace(Section,'-','0')),LEN(replace(Section,'-','0')))) -- numerical sort

是否可以用两种语言进行排序?

2 个答案:

答案 0 :(得分:2)

这适用于 SQL Server 2012

有点奇怪,但它适用于给定的样本:

DECLARE @xml xml
;WITH cte AS (
SELECT *
FROM (VALUES
(N'AHU-1-1'),(N'AHU-1-10'),(N'AHU-1-1-1'),(N'AHU-1-1-2'),(N'AHU-1-2'),
(N'AHU-1-3'),(N'AHU-1-8'),(N'AHU 1'),(N'AHU 11'),(N'AHU 2'),
(N'賃貸人側 1連絡先'),(N'更新連絡先')
) as t(section)
)


SELECT @xml = (
    SELECT CAST('<i id="'+section +'">'+ REPLACE('<b>'+REPLACE(section,'-','</b><b>')+'</b>',' ','</b><b>') +'</i>' as xml)
    FROM cte
    FOR XML PATH('')
)

SELECT section
FROM (
    SELECT  i.b.value('@id','nvarchar(20)') as section,
            i.b.value('b[1]','nvarchar(20)') as a,
            TRY_CAST(i.b.value('b[2]','nvarchar(20)') as int) as b,
            TRY_CAST(i.b.value('b[3]','nvarchar(20)') as int) as c,
            TRY_CAST(i.b.value('b[4]','nvarchar(20)') as int) as d
    FROM @xml.nodes('/i') as i(b)
    ) as p
ORDER BY (CASE WHEN b IS NULL and c IS NULL and d is NULL THEN 1 ELSE 0 END), d, c, b

输出:

section
AHU 1
AHU 2
AHU 11
AHU-1-1
AHU-1-2
AHU-1-3
AHU-1-8
AHU-1-10
AHU-1-1-1
AHU-1-1-2
賃貸人側 1連絡先
更新連絡先

对于 SQL Server 2008 及以上使用:

SELECT section
FROM (
    SELECT  i.b.value('@id','nvarchar(20)') as section,
            i.b.value('b[1]','nvarchar(20)') as a,
            i.b.value('b[2] cast as xs:int ?','int') as b,
            i.b.value('b[3] cast as xs:int ?','int') as c,
            i.b.value('b[4] cast as xs:int ?','int') as d
    FROM @xml.nodes('/i') as i(b)
    ) as p
ORDER BY (CASE WHEN b IS NULL and c IS NULL and d is NULL THEN 1 ELSE 0 END), d, c, b

答案 1 :(得分:0)

您可以在订单的末尾添加collate WHATEVER_COLLATION ...

我不确定您要使用的具体排序规则,不知道您的数据,但是您应该在这里找到有关差异的参考:https://msdn.microsoft.com/en-us/library/ff848763.aspx