[英]SQL ORDER BY dilemma with numbers
我有一個表,其中包含varchar數據類型。 最多可容納128個字符。
我正在嘗試按字母順序對其進行排序,但除了一件小事之外,它都可以正常工作。
當我嘗試保存數字和字母的混合形式時,它將返回“文字”字母順序,這意味着11排在2之前。
我已經閱讀了互聯網上幾乎所有的答案,但是它們都是無法專門解決我的問題的解決方法。
我想排序的值的示例
Apartment
House
Dog
Cat
18 years old
2 years old
1 year old
但我希望它看起來像這樣。
1 year old
2 years old
18 years old
Apartment
Cat
Dog
House
它跨越一個大型數據庫,我不能只將數字值與文本值分開。
也可以使用該程序的用戶可以用字母數字字符對其進行修改。
關於我的問題有什么建議嗎? 謝謝。
這是我在SQL Server中嘗試過的東西。 它既不優雅也不適合生產,但可能會給您一個想法。
SELECT StringValue,
CAST(SUBSTRING(StringValue, StartPos, EndPos - StartPos) AS INT) AsNumber,
SUBSTRING(StringValue, StartPos, EndPos - StartPos) NumberToken,
SUBSTRING(StringValue, EndPos, 1000) Rest,
StartPos,
EndPos
FROM
(SELECT
StringValue,
PATINDEX('[0-9]%', StringValue) StartPos,
PATINDEX('%[^0-9]%', StringValue) EndPos
FROM
(SELECT 'abc123xyz' StringValue
UNION SELECT '1abc'
UNION SELECT '11abc'
UNION SELECT '2abc'
UNION SELECT '100 zasdfasd') Sub1
) Sub2
ORDER BY AsNumber, Rest
結果:
StringValue AsNumber NumberToken Rest StartPos EndPos abc123xyz 0 abc123xyz 0 1 1abc 1 1 abc 1 2 2abc 2 2 abc 1 2 11abc 11 11 abc 1 3 100 zasdfasd 100 100 zasdfasd 1 4
我將按照以下方式進行處理...
首先,編寫一個表達式將數字內容轉換為整數,例如
select CAST(SUBSTRING(<field>',1,instr(<field>',' ') as INT),<field>
然后,我將使用UNION ALL語句,如下所示
SELECT CAST(SUBSTRING(<field>',1,instr(<field>',' ') as INT),<field>,A.*
FROM <table> A
WHERE <field> LIKE <regular expression to get fields beginning with numbers>
UNION ALL
SELECT 999999,<field>,A.*
FROM <table> A
WHERE <field> NOT LIKE <regular expression to get fields beginning with numbers>
ORDER BY 1,2,3
這些數字將首先以數字順序出現。 正弦所有的alpha數據都具有相同的數字鍵,它將按字母順序顯示在數字之后...只需確保將alpha虛擬鍵(999999)設置得足夠大,可以跟在所有數字鍵之后...
我在這台機器上沒有mySQL,但是希望這可以給您足夠的開始解決它的方法
您應該通過執行以下操作來擺脫困境:
order by right(replicate(' ',30)+Column_name,30)
嘗試以下命令:
ORDER BY RIGHT(REPLICATE('0',128)+value,128)
我的測試:
DECLARE @T TABLE
(
value VARCHAR(128)
)
INSERT INTO @T VALUES('Apartment'),
('House'),
('Dog'),
('Cat'),
('18 years old'),
('2 years old'),
('1 year old'),
('12 horses'),
('1 horse')
SELECT * FROM @T
ORDER BY RIGHT(REPLICATE('0',128)+value,128)
結果:
Cat
Dog
House
1 horse
12 horses
Apartment
1 year old
2 years old
18 years old
如果您發現這種情況不起作用,請將其與您想要的排序順序一起發布,我可以看看是否有解決方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.