如何在SSRS中订购以字符串形式给出的月份

时间:2018-10-17 11:20:16

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

如何在SSRS查询中获得数月(以字符串为单位)的订单。 我在下拉列表中使用month作为参数。

此代码似乎无法正常工作。

SELECT DATENAME(month, DATEADD(month, 6, getdate())) AS MonthName

UNION

SELECT DATENAME(month, DATEADD(month, 7, getdate())) AS MonthName

UNION

SELECT DATENAME(month, DATEADD(month, 8, getdate())) AS MonthName

UNION

SELECT DATENAME(month, DATEADD(month, 9, getdate())) AS MonthName

ORDER BY
  CASE MonthName
     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
     ELSE 0
  END

3 个答案:

答案 0 :(得分:1)

简单地说,不要那样做。如果要按日历中显示的顺序(而不是字母顺序)进行排序,则需要能够访问该数据:

SELECT DATENAME(MONTH, DATEADD(MONTH, V.I,GETDATE())) AS [MonthName]
FROM (VALUES(6),(7),(8),(9)) V(I)
ORDER BY V.I;

答案 1 :(得分:1)

我不确定您的期望如何,但是无论如何您都可以尝试:

select * from
(SELECT DATENAME(month, DATEADD(month, 6, getdate())) AS MonthName
UNION
SELECT DATENAME(month, DATEADD(month, 7, getdate())) AS MonthName
UNION
SELECT DATENAME(month, DATEADD(month, 8, getdate())) AS MonthName
UNION
SELECT DATENAME(month, DATEADD(month, 9, getdate())) AS MonthName
) a
ORDER BY
CASE a.MonthName
 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
 ELSE 0
END

答案 2 :(得分:0)

我将使用VALUES简化此过程。使用您的逻辑:

SELECT v.MonthName
FROM (VALUES (DATENAME(month, DATEADD(month, 6, getdate()))), 
             (DATENAME(month, DATEADD(month, 7, getdate()))),
             (DATENAME(month, DATEADD(month, 8, getdate()))),
             (DATENAME(month, DATEADD(month, 9, getdate())))
     ) V(MonthName)
ORDER BY
  CASE MonthName
     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
     ELSE 0
  END;

但是,您可以将其进一步简化为:

SELECT v.MonthName
FROM (VALUES (DATENAME(month, DATEADD(month, 6, getdate()))), 
             (DATENAME(month, DATEADD(month, 7, getdate()))),
             (DATENAME(month, DATEADD(month, 8, getdate()))),
             (DATENAME(month, DATEADD(month, 9, getdate())))
     ) V(MonthName)
ORDER BY cast(MonthName + '1, 2000' as date);