Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

sql - Complex sort of field "string - number - string"

Basically, I am trying to sort a table by its name. The table is relatively big, but I am posting only one column, for sake of example. The Column is Station below

Station
===
ANTIL WELL 1
ANTIL WELL 2
BASELINE & CALIFORNIA WELL
EPA WELL 6
EPA WELL 7
EPA WELL 108
EPA WELL 109
EPA WELL 110
EPA WELL 111
EPA WELL 112
EPA WELL 108S

The sort above was achieved by me trying this:

order by left(station,LEN(station) -PATINDEX('%[^0-9]%',REVERSE(station))+1)
,CONVERT(int,REVERSE(LEFT(REVERSE(station), PATINDEX('%[^0-9]%',REVERSE(station)) - 1)))

However, I just can't sort that EPA WELL 108S. I need it to go between EPA WELL 108 and EPA WELL 109, I tried many many different ways.

Also the list of the stations goes on after EPA.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This solution is more reliable than the chosen answer. This answer may not give the expected answer if there is more than 1 number like 'EPA WELL 5 7' in station. This solution is padding the number with '0's so the comparison will consider all numbers 8 digits.

DECLARE  @Table1 table([station] varchar(26))

INSERT INTO @Table1
    ([station])
VALUES
    ('ANTIL WELL 2'),
    ('ANTIL WELL 1'),
    ('BASELINE & CALIFORNIA WELL'),
    ('EPA WELL 7'),
    ('EPA WELL 6'),
    ('EPA WELL 108'),
    ('EPA WELL 109'),
    ('EPA WELL 110'),
    ('EPA WELL 111'),
    ('EPA WELL 112'),
    ('EPA WELL 108S'),
    ('EPA WELL 111108')
;

SELECT station
FROM @table1
ORDER BY 
CASE WHEN station not like '%[0-9]%' THEN station ELSE
   STUFF(station, PATINDEX('%[0-9]%',station), 0, replicate('0', 
   PATINDEX('%[0-9]%',station) - len(station) + PATINDEX('%[0-9]%',reverse(station)) + 6))
END

*GoatCD's answer will not give the correct order in my test data.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...