0

任何人都可以帮助解决这个问题,我正在尝试从表中选择最近 12 个月的日期,然后更改格式以使日期显示为:

2013 年 2 月

2013 年 1 月等

我可以将格式更改为上述格式,但这会将日期更改为字符串,从而无法订购 DESC。

我怎样才能保持上述格式,并且仍然按 desc 排序

SELECT DISTINCT TOP 12 
--CONVERT(date, NewsDatePosted, 120) AS ArchiveTravelNewsByMonth
--CONVERT(CHAR(4), NewsDatePosted, 100) + CONVERT(CHAR(4), NewsDatePosted, 120) AS MY
--DatePart(Year,NewsDatePosted) AS YearPosted 
--datename(month,NewsDatePosted) + ' ' + DatePart(Year,NewsDatePosted) AS YearPosted
FROM dbo.at_News
order by ArchiveTravelNewsByMonth DESC

谢谢

乔治


SELECT DISTINCT TOP 12 SUBSTRING(CONVERT(VARCHAR(11), NewsDatePosted, 113), 4, 8)
AS ArchiveTravelNewsByMonth,
NewsDatePosted
FROM dbo.at_News
ORDER BY CONVERT(DATETIME, CONVERT(CHAR(4), NewsDatePosted, 100) + CONVERT(CHAR(4), NewsDatePosted, 120))
4

2 回答 2

0

请尝试通过添加 order by 子句和内部选择来尝试

SELECT 
    ArchiveTravelNewsByMonth, 
    NewsDatePosted
FROM(
    SELECT DISTINCT TOP 12 SUBSTRING(CONVERT(VARCHAR(11), NewsDatePosted, 113), 4, 8) AS ArchiveTravelNewsByMonth,
        NewsDatePosted
    FROM dbo.at_News)x
ORDER BY CONVERT(DATETIME, ArchiveTravelNewsByMonth)
于 2013-01-16T11:08:11.307 回答
0
  create table at_News(NewsDatePosted datetime,Row int identity(1,1))

  Insert into at_News values('2011-01-01')
  Insert into at_News values('2006-10-25')
  Insert into at_News values('2012-09-10')
  Insert into at_News values('2002-06-20')
  Insert into at_News values('2008-12-01')
  Insert into at_News values('2008-10-01')
  Insert into at_News values('2008-04-01')

  select CONVERT(CHAR(4), NewsDatePosted, 100) + CONVERT(CHAR(4), NewsDatePosted, 120)      from  at_News order by NewsDatePosted desc

使用ORDER BY CLAUSE 中的日期时间列,不使用任何格式

于 2013-01-16T11:28:41.173 回答