简体   繁体   English

在SQL Server 2008中按月排序

[英]Order by Month in SQL server 2008

I want to order my table based on month. 我想根据月份订购我的桌子。 .. But the thing is order by month during the fiscal year... ie., April to march . ..但是事情是在财政年度中按月排序的,即4月进行。 thanks in advance 提前致谢

You can order by anything you can write an expression for... In your case Try: 您可以按可以为...写表达式的任何方式进行排序...在您的情况下,请尝试:

  ... Order By (Month(somedate) + 8) % 12

EDIT: Should be 8 not 9... 编辑:应该是8而不是9 ...

I suggest something similar to Jakob's answer, only more along the lines of: 我建议与Jakob的回答类似的内容,但仅限于以下方面:

((month(somedate) - 4) + 12) % 12

Subtracting 4 shifts April to the beginning. 从4月开始减去4个班次。 Adding 12 handles pre-April months, and the modulus corrects the previous step for post-April months. 在4月之前增加12个句柄,并且模数会在4月之后修正上一个步骤。

This will produce results in the range of 0 - 11. Also the x - 4 + 12 step can be simplified to x + 8 ; 这将产生0到11范围内的结果。同样, x - 4 + 12步长可以简化为x + 8 I thought I'd leave it unabbreviated for the purpose of the explanation. 为了说明起见,我认为我将其省略。

A lot of the above will work, but if you find yourself doing a lot of date manipulation with different calendars it might be worth creating a separate calendar table as a lookup. 上面的许多方法都可以使用,但是如果您发现自己使用不同的日历进行了大量的日期操作,则可能值得创建一个单独的日历表作为查找。

Something like 就像是


CREATE TABLE [dim].[Date](
    [DateSK] [int] NOT NULL,
    [Date] [datetime] NOT NULL,
    [Year] [int] NOT NULL,
    [Month] [int] NOT NULL,
    [Day] [int] NOT NULL,
    [WeekDayName] [varchar](9) NOT NULL,
    [MonthName] [varchar](9) NOT NULL,
    [QuarterNumber] [int] NOT NULL,
    [FinancialYear] [int] NOT NULL,
    [FinancialMonth] [int] NOT NULL,
    [MonthLength] [int] NOT NULL,
    [DaysRemainingInMonth] [int] NOT NULL,
    [DaysRemainingInYear] [int] NOT NULL,
    [IsLeapYear] [bit] NOT NULL,
    [DaysInYear] [int] NOT NULL,
    [DayOfYear] [int] NOT NULL,

    etc, etc.
)

USE my_db

SELECT 
    MONTH(t1.expiry) as SortOrder, 
    DATENAME(MONTH,t1.expiry) AS ExpiryMonth,  
    COUNT(*) AS Count

FROM 
    table1 t1 LEFT JOIN table2 t2 ON t2.c1 = t1.c1

WHERE 
    YEAR(t1.expiry) = '2012' AND t2.c2 = 'X'

GROUP BY
    MONTH(t1.expiry),
    DATENAME(MONTH,t1.expity)

ORDER BY 
    SortOrder ASC

I guess a more generic solution like this one is better than always using a custom sort. 我猜想像这样的更通用的解决方案比总是使用自定义排序更好。 There is not much cost involved in terms of processing time. 就处理时间而言,所涉及的成本不高。

SELECT
Column1,
Column2,
Column3,
SomeDate,
CASE MONTH(SomeDate)
  WHEN  4 THEN  1
  WHEN  5 THEN  2
  WHEN  6 THEN  3
  WHEN  7 THEN  4
  WHEN  8 THEN  5
  WHEN  9 THEN  6
  WHEN 10 THEN  7
  WHEN 11 THEN  8
  WHEN 12 THEN  9
  WHEN  1 THEN 10
  WHEN  2 THEN 11
  WHEN  3 THEN 12
END as FiscalMonth
FROM myTable
ORDER BY FiscalMonth

How about this: 这个怎么样:

SELECT ...
ORDER BY MONTH(SomeDate) % 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM