任何人都可以帮助解决这个问题,我正在尝试从表中选择最近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))
答案 0 :(得分: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)
答案 1 :(得分: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中使用日期时间列,不带任何格式。