开发者

SELECT DISTINCT on datetime

I need to display distinct values of a datetime field called datetimestamp from a SQLServer 2005 table in the MMM YYYY format. I also need them to be sorted in chronological order.

So far I have this:

Select distinct CONVERT(CHAR(4), datetimestamp, 100) + CONVERT(CHAR(4), datetimestamp, 120) as MonthYear from TableName order by MonthYear

The "order by" of course sorts it in alpha order due to the conversion.

 Apr 2009 
 Dec 2009 
 Feb 2009

How do I get it to sort i开发者_开发技巧t in chronological order?

Feb 2009
Apr 2009
Dec 2009

Thanks.


edit2: It looks like you'll need to pull back more than one column. This uses just the subquery from the previous attempt:

    select distinct DATEPART(year,datetimestamp) as year, 
           DATEPART(month,datetimestamp) as month,
           CONVERT(CHAR(4), datetimestamp, 100) 
           + CONVERT(CHAR(4), datetimestamp, 120) as MonthYear
    from TableName order by DATEPART(year,datetimestamp), 
                            DATEPART(month,datetimestamp)


take a look a this post.

Get month and year from a datetime in SQL Server 2005

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜