我必须编写一个查询来按特定顺序选择月份,例如从3月到2月,或2月到1月。我不能使用存储过程。我必须使用SELECT,并在数据库中存储月份的名称,如'january','febrary','march'等...
在获取月份时,我只需要前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
答案 0 :(得分: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
答案 1 :(得分: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))
答案 2 :(得分:0)
一种选择是更改ORDER BY
:
ORDER BY Cast(mon as int)
祝你好运。
答案 3 :(得分: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)