我试图在没有太多运气的情况下查询和排序列。我的数据看起来像这样,与前面的" WP"。
一致应显示为
WP1-WP2
WP2-WP3
WP10-WP11
WP10-WP12
实际显示为
WP1-WP2
WP10-WP11
WP10-WP12
WP2-WP3
我尝试调整此处找到的几个答案但没有成功。
问题是如何对此列表进行排序?
编辑:我在查询中使用了distinct,不确定这是否会影响我遇到的问题
答案 0 :(得分:2)
试试这个,
select *
from myStringSorting
order by Cast(Replace(Substring(mycol,0,CHARINDEX('-',mycol)),'WP','') as Int) asc
,Cast(Replace(Substring(mycol,CHARINDEX('-',mycol) + 1,LEN(mycol)),'WP','') as Int) asc
点击此链接http://sqlfiddle.com/#!3/ca45f/5
使用DISTINCT,
With CTE as
(
select distinct mycol
from myStringSorting
)
select * from CTE
order by Cast(Replace(Substring(mycol,0,CHARINDEX('-',mycol)),'WP','') as Int) asc
,Cast(Replace(Substring(mycol,CHARINDEX('-',mycol) + 1,LEN(mycol)),'WP','') as Int) asc
使用DISTINCT,没有CTE,使用子查询,
Select a.mycol from
(
select distinct mycol
from myStringSorting
)as a
order by Cast(Replace(Substring(a.mycol,0,CHARINDEX('-',a.mycol)),'WP','') as Int) asc
,Cast(Replace(Substring(a.mycol,CHARINDEX('-',a.mycol) + 1,LEN(a.mycol)),'WP','') as Int) asc
答案 1 :(得分:1)
另一种方法
select * from myStringSorting
order by len(mycol),mycol