monthtext <-----(column Name in varchar)
'2016july'
'2016september'
'2016december'
'2016january'
'2017february'
'2017june'
'2017march'
我想通过升序或降序排序,而不是按字母顺序排序。 它应该考虑分拣月份和年份
升序答案应该像
'2016 january'
'2016 july'
'2016 saptember'
'2016 december'
'2017 february'
'2017 march'
'2017 june'
答案 0 :(得分:1)
如果所有日期都有效,您可以使用此项:
SELECT monthtext
FROM
(values
('2016july'),('2016september'),('2016december'),('2016january'),
('2017february'),('2017june'),('2017march')) x(monthtext)
ORDER BY cast(monthtext as date)
答案 1 :(得分:0)
这样的事情:
您还应在case
声明
select t.* from (
select '2016july' as str union all
select '2016september' union all
select '2016december' union all
select '2016january' union all
select '2017february' union all
select '2017june' union all
select '2017march'
)t
order by
cast( substring(str, 1, 4) as int),
case
when substring(str, 5, len(str)) = 'january' then 1
when substring(str, 5, len(str)) = 'february' then 2
when substring(str, 5, len(str)) = 'march' then 3
when substring(str, 5, len(str)) = 'june' then 6
when substring(str, 5, len(str)) = 'july' then 7
when substring(str, 5, len(str)) = 'september' then 9
when substring(str, 5, len(str)) = 'december' then 12
end
答案 2 :(得分:0)
您需要将其拆分为年份和年份。然后月份应用Order By子句。
<强>架构:强>
CREATE TABLE #TAB (NAME VARCHAR(50))
INSERT INTO #TAB
SELECT '2016july'
UNION ALL
SELECT '2016september'
UNION ALL
SELECT '2016december'
UNION ALL
SELECT '2016january'
UNION ALL
SELECT '2017february'
UNION ALL
SELECT '2017june'
UNION ALL
SELECT '2017march'
现在选择如下所示
SELECT NAME
, CAST(SUBSTRING(NAME, 1, PATINDEX('%[a-z]%',NAME)-1) AS INT) YEAROF
,DATEPART(MM, SUBSTRING(NAME,PATINDEX('%[a-z]%',NAME),LEN(NAME)) +' 01 2017') MONTHOF
FROM #TAB
ORDER BY YEAROF,MONTHOF
<强>结果:强>
+---------------+--------+---------+
| NAME | YEAROF | MONTHOF |
+---------------+--------+---------+
| 2016january | 2016 | 1 |
| 2016july | 2016 | 7 |
| 2016september | 2016 | 9 |
| 2016december | 2016 | 12 |
| 2017february | 2017 | 2 |
| 2017march | 2017 | 3 |
| 2017june | 2017 | 6 |
+---------------+--------+---------+