SELECT varcharColumn
FROM tableA
ORDER BY varcharColumn ASC
给我
1060006-1
1060006-10
1060006-11
1060006-12
1060006-13
1060006-15
1060006-16
1060006-17
1060006-18
1060006-19
1060006-20
1060006-2
等
我想要的是
1060006-1
1060006-2
1060006-3
等
可以订购吗?或者我需要一些更有趣的东西?
使用这个给了我下面的结果:
ORDER BY
CASE WHEN varcharcolumn like '%-%' THEN 1 ELSE 2 END,
LEN(varcharcolumn)
答案 0 :(得分:4)
我认为有效的方法是使用Order By
<强>架构:强>
CREATE TABLE #TAB (VARCHARCOLUMN VARCHAR(20))
INSERT INTO #TAB
SELECT '1060006-1'
UNION ALL
SELECT '1060006-10'
UNION ALL
SELECT '1060006-11'
UNION ALL
SELECT '1060006-12'
UNION ALL
SELECT '1060006-13'
UNION ALL
SELECT '1060006-15'
UNION ALL
SELECT '1060006-16'
UNION ALL
SELECT '1060006-17'
UNION ALL
SELECT '1060006-18'
UNION ALL
SELECT '1060006-19'
UNION ALL
SELECT '1060006-20'
UNION ALL
SELECT '1060006-2'
现在按部分-
拆分varchar列并获取订单
SELECT VARCHARCOLUMN
,CAST(SUBSTRING(VARCHARCOLUMN,1,CHARINDEX('-', VARCHARCOLUMN)-1) AS BIGINT) AS PART1
,CAST(SUBSTRING(VARCHARCOLUMN,CHARINDEX('-', VARCHARCOLUMN)+1,LEN(VARCHARCOLUMN)) AS INT) AS PART2
FROM #TAB
ORDER BY PART1, PART2
这将返回
+---------------+---------+-------+
| VARCHARCOLUMN | PART1 | PART2 |
+---------------+---------+-------+
| 1060006-1 | 1060006 | 1 |
| 1060006-2 | 1060006 | 2 |
| 1060006-10 | 1060006 | 10 |
| 1060006-11 | 1060006 | 11 |
| 1060006-12 | 1060006 | 12 |
| 1060006-13 | 1060006 | 13 |
| 1060006-15 | 1060006 | 15 |
| 1060006-16 | 1060006 | 16 |
| 1060006-17 | 1060006 | 17 |
| 1060006-18 | 1060006 | 18 |
| 1060006-19 | 1060006 | 19 |
| 1060006-20 | 1060006 | 20 |
+---------------+---------+-------+
答案 1 :(得分:1)
ORDER BY
CASE WHEN varcharcolumn like '%-%' THEN 1 ELSE 2 END,
LEN(varcharcolumn), varcharcolumn
通过这种方式,您可以先获得破折号;那么LEN(XX)
部分是这样的,1-10在1-1之后不会出现,而不需要转换为十进制。无论如何,您可以自由删除排序
如果你只想要破折号出现,那么也许你应该做一个where子句。
答案 2 :(得分:0)