查询订单的问题

时间:2018-05-17 03:53:58

标签: sql-server tsql sql-order-by sql-server-2014

我必须订购以下类别:

1
2
3
4
5
10
11
12
6A
6B
6C
6D
7A
7B

如何通过SQL查询完成此操作?

我试过了:

SELECT TABLE_NAME
FROM USER_TAB_COLUMNS
WHERE NOT COLUMN_NAME LIKE '%OBJECT_NO%'
ORDER BY COLUMN_ID;

但是他们这样命令:

COLUMN_ID='OBJECT_NO'.

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

您可以使用标量值函数(有关标量值函数的更多信息here)来删除类别中的字母'名称(有关此特定函数here的更多信息)并使用结果对数据进行排序:

--1. declare a new function that removes all letters from your category name
--1.1 if the function already exists delete it
if OBJECT_ID('fx_remove_letters') is not null
drop function fx_remove_letters

go
--1.2 create a function to remove all letters (CHAR(65) is letter A, char(90) is letter Z)
create function fx_remove_letters(@str NVARCHAR(max))
returns  NVARCHAR(max)
as
begin
    DECLARE @loop INT
    SET @loop = 0
    WHILE @loop < 26
        BEGIN
        SET @str = REPLACE(@str, CHAR(65 + @loop), '')
        SET @loop = @loop + 1
        END
    return @str
end
go
--2. this table variable holds your categories in a random order
declare @tmp table (category_name nvarchar(10))

--3. populate the test table variable 
insert into @tmp 
values('6D'),('2'),('3'),('12'),('5'),('6C'),('6B'),
      ('1'),('7A'),('4'),('7B'),('10'),('11'),('6A')

--4. select your data ordering them with the function we defined at the beginning
select category_name 
from @tmp 
order by cast(dbo.fx_remove_letters(category_name) as int), category_name

这是订购前的表格:

enter image description here

现在order by之后的结果:

enter image description here

答案 1 :(得分:0)

这有用吗?

SELECT category_name
FROM #Table1
ORDER BY 
    CASE ISNUMERIC(category_name) 
        WHEN 1 THEN REPLICATE('0', 10 - LEN(category_name)) + category_name       
        ELSE REPLICATE('0', 10 - LEN(category_name)+1) + category_name     
    END

如果您在输入中有&#39; 6AA&#39;,&#39; 6AB&#39; ...等,您可以使用以下查询:

SELECT category_name
    FROM #Table1
    ORDER BY 
        CASE 
            WHEN ISNUMERIC(category_name) =1 
                THEN REPLICATE('0', 10 - LEN(category_name)) + category_name
            ELSE 
                REPLICATE('0', 10 - LEN(category_name)+LEN(STUFF(category_name, PATINDEX('%[^a-zA-Z]%',category_name),1,''))) + category_name   
        END