在SQL Server中的月Wise数据

时间:2015-02-02 07:08:26

标签: sql sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012

我对SQL服务器有一点怀疑。请告诉我如何在SQL Server中显示月份数据以解决此问题。 表数据如下所示:

月数据类型为varchar(20),ID为int

表:月份

month     |id
April     |1
January   |2
March     |3
Feburary  |4
August    |7
December  |5
May   |6
June      |2
July      |3
August    |NULL
September |2
Octomber  |1
November  |3
June      |8

根据这些数据,我想要输出如下:

month      |id
January    |2
Feburary   |4
March      |3
April      |1
May    |6
June       |2
June       |8
July       |3
August     |NULL
August     |7
September  |2
Octomber   |1
November   |3
December   |5

我尝试过以下查询:

select * 
from  months   
order by datepart(mm,[month]+ ' 01 2010'),id

但它显示如下错误:

  

msg 241,Level 16,State 1,Line 1转换时转换失败   字符串的日期和/或时间。

请告诉我,如何在SQL Server中解决这个问题?

1 个答案:

答案 0 :(得分:0)

CASE

中使用ORDER BY
SELECT * 
    FROM YOURTABLE
    ORDER BY 
    CASE WHEN [month] = 'January' THEN 0             
         WHEN [month] = 'February' THEN 1
         WHEN [month] = 'March' THEN 2
         WHEN [month] = 'April' THEN 3
         WHEN [month] = 'May' THEN 4
         WHEN [month] = 'June' THEN 5
         WHEN [month] = 'July' THEN 6
         WHEN [month] = 'August' THEN 7
         WHEN [month] = 'September' THEN 8
         WHEN [month] = 'October' THEN 9
         WHEN [month] = 'November' THEN 10
         WHEN [month] = 'December' THEN 11
    END
 FROM YOUURTABLE

编辑:

您的February拼写错误。