按Varchar列排序,其中包含带破折号的数字(1060006-19)

时间:2017-04-04 04:59:37

标签: sql sql-server tsql

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)

enter image description here

3 个答案:

答案 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)

Bennioe让我走上了正确的道路。最后这给了我想要的输出。

SELECT varcharcolumn 
FROM TableA
order by LEN(varcharcolumn ) asc, varcharcolumn asc

enter image description here