sql server order by子句

时间:2016-04-12 10:17:40

标签: sql sql-server

以下是我的询问:

SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED]

它给了我以下结果:

query result

问题是如果我正在做order by MonthCycle那么因为它是一个字符串,所以它使用了月份的第一个字母进行排序,但我希望order by基于月份Jan {1}}应该是第一个,然后是Feb,依此类推。

5 个答案:

答案 0 :(得分:2)

使用case表达式返回月份编号:

SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED]
order by case left(monthcycle,3) when 'Jan' then 1
                                 when 'Feb' then 2
                                 ...
         end

答案 1 :(得分:2)

问题没有说明报告是否会跨越几年,但如果是这样,我会使用这样的东西:

ORDER BY CONVERT(DATETIME, '1 ' + REPLACE(monthCycle, '''', ' '))

答案 2 :(得分:1)

SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED]
ORDER BY CASE 
  WHEN LEFT(MONTHCYCLE,3) = 'Jan' then 1
  WHEN LEFT(MONTHCYCLE,3) = 'Feb' then 2
  WHEN LEFT(MONTHCYCLE,3) = 'Mar' then 3
  WHEN LEFT(MONTHCYCLE,3) = 'Apr' then 4
  WHEN LEFT(MONTHCYCLE,3) = 'May' then 5
  WHEN LEFT(MONTHCYCLE,3) = 'Jun' then 6
  WHEN LEFT(MONTHCYCLE,3) = 'Jul' then 7
  WHEN LEFT(MONTHCYCLE,3) = 'Aug' then 8
  WHEN LEFT(MONTHCYCLE,3) = 'Sep' then 9
  WHEN LEFT(MONTHCYCLE,3) = 'Oct' then 10
  WHEN LEFT(MONTHCYCLE,3) = 'Nov' then 11
  WHEN LEFT(MONTHCYCLE,3) = 'Dec' then 12
  ELSE 0 END;

答案 3 :(得分:1)

您可以使用DATEPART

像这样,

SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED] Order by DATEPART(MM,'01'+MONTHCYCLE)

OR

SELECT * FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED] Order by DATEPART(MM,'01'+Replace(MONTHCYCLE,'''',''))

答案 4 :(得分:0)

另一种方式:)

DECLARE @d as date = '2016-01-01'
;WITH months AS (
SELECT  1 as [Month],
        LEFT(DATENAME(Month,@d),3) as MName
UNION ALL
SELECT  [Month] + 1,
        LEFT(DATENAME(Month,DATEADD(Month,[Month],@d)) ,3) 
FROM months 
WHERE [Month] + 1 <= 12
)

SELECT c.*
FROM [TEMPDB].[dbo].[##TEMPMSICHARTFORMATTED] c
LEFT JOIN months m 
    ON c.MONTHCYCLE LIKE m.MName +'%'
ORDER BY RIGHT(c.MONTHCYCLE,2) ASC, m.[Month] ASC

输出:

MONTHCYCLE TARGET Corp Stnd   Local       OF Stnd
---------- ------ ----------- ----------- -----------
Jan'16            2           1           1
Feb'16            1           1           1
Mar'16            2           3           1
Apr'16            4           3           NULL

(4 row(s) affected)