我正在尝试安排一个包含以下值的列:
6-3
11-1
3
8-5
5
6-2
1
7
11-4
8-12
2
我希望他们像这样安排:
1
2
3
5
7
6-2
6-3
8-5
8-12
11-1
11-4
我现在有这个查询:
select column_name from database_name.dbo.table_name
order by
(case when (BOX_NO not like '%-%')
then -1 when (BOX_NO like '%-%')
then cast(SUBSTRING(reverse(BOX_NO), LEN(BOX_NO)-(CHARINDEX('-', reverse(BOX_NO))-2), 0) as int) end),
(case when (column_name not like '%-%')
then cast(column_name as int)
when (column_name like '%-%')
then cast(SUBSTRING(column_name, LEN(column_name)-(CHARINDEX('-', reverse(column_name))-2), 8000) as int) end)
我疯了。如果有人能帮助我那会很好。谢谢!
答案 0 :(得分:0)
Woopsy雏菊!现在一切都很好。第一个案例错了。应该没有第二次逆转。搜索应该从8000开始而不是0.我的不好!
(case when (column_name not like '%-%') then 0 when (column_name like '%-%') then cast(SUBSTRING(reverse(column_name), LEN(column_name)-(CHARINDEX('-', column_name)-2), 8000) as int) end),
答案 1 :(得分:0)
declare @test table ( value varchar(10))
insert @test values ('6-3'),
('11-1'),
('3'),
('8-5'),
('5'),
('6-2'),
('1'),
('7'),
('11-4'),
('8-12'),
('2')
select
T2.value,
case when CHARINDEX('-', T1.value) = 0 then cast(T1.value as int) else cast(LEFT(T1.value, CHARINDEX('-', T1.value) - 1) as int) end,
case when CHARINDEX('-', T1.value) = 0 then 0 else cast(substring(T1.value, CHARINDEX('-', T1.value) + 1, 10) as int) end
from @test T1, @test T2
where T1.value = T2.value
order by 2, 3