0

我必须编写一个查询以按特定顺序选择月份,例如从 3 月到 2 月,或从 2 月到 1 月。我不能使用存储过程。我必须使用 SELECT 并在数据库中存储月份的名称,如“一月”、“二月”、“三月”等......

在获取月份时,我只需要前 3 个字符。

结果应该是

jan 1
feb 2
mar 3
apr 4
may 5
jun 6
jul 7
aug 8
sep 9
oct 10
nov 11
dec 12

使用此查询后

Select distinct upper(convert(varchar(3),datename(MONTH,InvoiceDate))) as monthName,upper(convert(nvarchar,datepart(mm,InvoiceDate))) as 
    mon  
from OpenInvoiceDetails 
order by mon

我明白了

jan 1
oct 10
nov 11
dec 12
feb 2
mar 3
apr 4
may 5
jun 6
jul 7
aug 8
sep 9
4

4 回答 4

0

我在这里做了很多假设,但是这样的事情会起作用:

    Create Table Months
(
    DateColumn varchar(20)
)

INSERT INTO Months

SELECT 'January' 
UNION
SELECT 'February'
UNION
SELECT 'March'
UNION
SELECT 'April'
UNION
SELECT'May' 
UNION
SELECT 'June' 
UNION
SELECT 'July' 
UNION
SELECT 'August'
UNION
SELECT 'September'
UNION
 SELECT'October' 
UNION
SELECT 'November'
UNION
SELECT 'December'

SELECT  DateColumn ,( CASE DateColumn
            WHEN 'January' THEN 1
            WHEN 'February' THEN 2
            WHEN 'March' THEN 3
            WHEN 'April' THEN 4
            WHEN 'May' THEN 5
            WHEN 'June' THEN 6
            WHEN 'July' THEN 7
            WHEN 'August' THEN 8
            WHEN 'September' THEN 9
            WHEN 'October' THEN 10
            WHEN 'November' THEN 11
            WHEN 'December' THEN 12
          END ) as [Month]
From Months
Order by Month

给你这个:

January 1
February    2
March   3
April   4
May 5
June    6
July    7
August  8
September   9
October 10
November    11
December    12

按月排序:

December    12
November    11
October 10
September   9
August  8
July    7
June    6
May 5
April   4
March   3
February    2
January 1
于 2013-01-31T06:30:02.297 回答
0

这不会是最佳的,但它应该解决无效的列名。

Select distinct upper(convert(varchar(3),datename(MONTH,InvoiceDate))) as monthName
,upper(convert(nvarchar,datepart(mm,InvoiceDate))) as mon 
from 
 OpenInvoiceDetails 
order by Len(convert(nvarchar,datepart(mm,InvoiceDate))),
convert(nvarchar,datepart(mm,InvoiceDate))
于 2013-01-31T06:34:21.773 回答
0

一种选择是更改您的ORDER BY

ORDER BY Cast(mon as int) 

祝你好运。

于 2013-01-31T06:37:03.497 回答
0

尝试使用此查询

    Select distinct
    upper(convert(varchar(3),datename(MONTH,daterecieved))) as monthName,
    datepart(mm,daterecieved)  as mon 
    from Donations 
    order by mon

    Select distinct
    upper(convert(varchar(3),datename(MONTH,InvoiceDate))) as monthName,
    Cast(upper(convert(nvarchar,datepart(mm,InvoiceDate)))  as int) as mon 
    from OpenInvoiceDetails 
    order by Cast(upper(convert(nvarchar,datepart(mm,daterecieved)))  as int)
于 2013-01-31T06:37:42.547 回答