我在数据库中有英寸大小的列 - 例如
1", 3/4", 15/16", 5/8" etc
因此,当我运行查询时,请说
SELECT *
FROM TB_Items
ORDER BY Size ASC
它返回:
1", 5/8" , 3/4" , 15/16"
但我需要
5/8", 3/4", 15/16", 1"
请帮忙
注意:Size
列数据类型为varchar
答案 0 :(得分:1)
根据需要添加更多尺寸
..ORDER BY
CASE WHEN inch_col = "5/8" THEN 1
WHEN inch_col = "3/4" THEN 2
WHEN inch_col = "15/16" THEN 3
WHEN inch_col = "1" THEN 4
ELSE 5 END
答案 1 :(得分:1)
如果尺寸< = 1"您可以使用相对复杂的表达式对结果集进行排序。创建计算持久列的更好方法。如果尺寸> 1种表达式要复杂得多
create table Item
(
Id int not null identity primary key,
Size varchar(100) not null
)
go
insert into Item (Size)
values ('1"'), ('3/4"'), ('15/16"'), ('5/8"');
go
select
id, size
from
Item
order by
CAST((CASE CHARINDEX('/', Size) WHEN 0 THEN SUBSTRING(Size, 1, LEN(Size) - 1) ELSE SUBSTRING(Size, 1, CHARINDEX('/', Size) - 1) END) as DECIMAL(18, 4)) /
CASE CHARINDEX('/', Size) WHEN 0 THEN 1 ELSE CAST(SUBSTRING(Size, CHARINDEX('/', Size) + 1, LEN(Size) - CHARINDEX('/', Size) - 1) as INT) END