简体   繁体   中英

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 . 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...

I suggest something similar to Jakob's answer, only more along the lines of:

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

Subtracting 4 shifts April to the beginning. Adding 12 handles pre-April months, and the modulus corrects the previous step for post-April months.

This will produce results in the range of 0 - 11. Also the x - 4 + 12 step can be simplified to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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