[英]Query ordering in SQL Server within sub number
當我通常這樣選擇時,我有一列數據類型為varchar
column
------
1
2
3
4Answer
4
5
1_1Answer
1_2Answer
2Answer
6
7
8
10Answer
9
10
我想要像這樣按編號和子編號排序結果
column
-----
1
1_1Answer
1_2Answer
2
2Answer
3
4
4Answer
5
6
7
8
9
10
10Answer
我有很多這樣的數據,子編號中有20多個
這稱為“自然排序”,大多數數據庫默認情況下不支持此功能。
就我而言,我在postgres中編寫了存儲過程以解決這個問題。 我不知道您的數據庫軟件是哪個。 谷歌的“ natsort”
更新:到PC。 這是我在postgres中使用的東西(部分在這里,在stackowerflow上找到):
/* Split the input text into contiguous chunks where no numbers appear,
and contiguous chunks of only numbers. For the numbers, add leading
zeros to 20 digits, so we can use one text array, but sort the
numbers as if they were big integers.
For example, human_sort('Run 12 Miles') gives
['Run ', '00000000000000000012', ' Miles']
*/
select array_agg(
case
when a.match_array[1]::text is not null
then a.match_array[1]::text
else lpad(a.match_array[2]::text, 20::int, '0'::text)::text
end::text)
from (
select regexp_matches(
case when $1 = '' then null else $1 end, E'(\\D+)|(\\d+)', 'g'
) AS match_array
) AS a
用法:`select .....按natsort(字段)排序
對於列出的示例數據,可以使用查詢
--Create example table to use
CREATE TABLE #Test ([Column] VarChar(50))
--Add example data to the example table
INSERT INTO #Test([Column]) VALUES
('1'),
('2'),
('3'),
('4Answer'),
('4'),
('5'),
('1_1Answer'),
('1_2Answer'),
('2Answer'),
('6'),
('7'),
('8'),
('10Answer'),
('9'),
('10')
--Select data from the table, ordering by the number part at the beginning of the column, and then by the whole column
SELECT [Column]
FROM #Test
ORDER BY
CASE
WHEN PATINDEX('%[_a-z]%', [Column]) = 0 THEN TRY_CONVERT(INT, [Column])
ELSE TRY_CONVERT(INT, LEFT([Column], PATINDEX('%[_a-z]%', [Column]) -1))
END,
[Column]
假設您只有一個子編號,則可以將前導數字加下划線轉換為十進制值,並按以下order by
:
order by convert(decimal(10, 4),
replace(left(column,
patindex('%[^0-9_]%', column + 'x') - 1
), '_', '.'
)
)
我不知道我是否搞砸了下面的查詢,但嘗試了一下。 我在下面的查詢中所表示的意思是單位數字/單詞的所有列作為組,而其他列作為子組。
Select column over
(Partition by
column where column
like '%Answer%' ) from
table group by column order by
column;
如果您碰巧使用oracle,則可以這樣做:
order by substr(your_column, 1, 1) asc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.